/* Rank Lyx - AI Writer / Create Content Brief */

const { useState, useEffect, useRef, useMemo } = React;

/* Current signed-in user and workspace are populated by auth-runtime.js. */
window.currentUser = window.currentUser || null;
window.currentWorkspace = window.currentWorkspace || null;

function getWritingRuntimeStatus() {
  const WA = typeof window !== 'undefined' ? window.WritingAgent : null;
  const appLLMAdapter = typeof window !== 'undefined' && typeof window.appLLMAdapter === 'function' ? window.appLLMAdapter : null;
  let hasLiveAdapterResult = false;
  try {
    hasLiveAdapterResult = !!(WA && typeof WA.hasLiveAdapter === 'function' && appLLMAdapter && WA.hasLiveAdapter({ llmAdapter: appLLMAdapter }));
  } catch (e) {
    hasLiveAdapterResult = false;
  }
  return {
    hasArticleStore: !!(typeof window !== 'undefined' && window.ArticleStore),
    hasWritingAgent: !!WA,
    hasGenerateArticleDraft: !!(WA && typeof WA.generateArticleDraft === 'function'),
    hasAppLLMAdapter: !!appLLMAdapter,
    hasLiveAdapterResult
  };
}

function logWritingRuntime(label, extra) {
  const s = getWritingRuntimeStatus();
  try {
    console.log('[DraftRuntime] ' + label + ' ' + JSON.stringify(Object.assign({
      'WritingAgent loaded': s.hasWritingAgent ? 'yes' : 'no',
      'appLLMAdapter loaded': s.hasAppLLMAdapter ? 'yes' : 'no',
      'generateArticleDraft available': s.hasGenerateArticleDraft ? 'yes' : 'no'
    }, extra || {}, s)));
  } catch (e) {}
  return s;
}

function waitForWritingRuntime(timeoutMs = 2500) {
  const started = Date.now();
  return new Promise((resolve) => {
    const tick = () => {
      const s = getWritingRuntimeStatus();
      if (s.hasArticleStore && s.hasWritingAgent && s.hasGenerateArticleDraft && s.hasAppLLMAdapter) return resolve(s);
      if (Date.now() - started >= timeoutMs) return resolve(s);
      setTimeout(tick, 80);
    };
    tick();
  });
}

const DRAFT_GENERIC_PUBLIC_ERROR = 'Something went wrong while writing the article. Please try again.';

function getDraftPublicErrorMessage(result) {
  const message = result && result.publicError && typeof result.publicError.message === 'string'
    ? result.publicError.message.trim()
    : '';
  return message || DRAFT_GENERIC_PUBLIC_ERROR;
}

if (typeof window !== 'undefined') {
  window.getDraftPublicErrorMessage = getDraftPublicErrorMessage;
}

if (typeof window !== 'undefined') {
  window.addEventListener('load', () => {
    setTimeout(() => { logWritingRuntime('page-load'); }, 0);
  });
}

/* ------------------------------------------------------------------ */
/* Lucide refresh - call after any render that adds new <i data-lucide> */
function useLucide(deps) {
  useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  }, deps);
}

/* ------------------------------------------------------------------ */
/* Sidebar */
const PROFILE_MENU = [
{ id: 'settings', icon: 'settings', label: 'Settings' },
{ id: 'credits', icon: 'gauge', label: 'Article Usage' },
{ id: 'help', icon: 'life-buoy', label: 'Help' },
{ id: 'contact', icon: 'mail', label: 'Contact Us' },
{ id: 'feedback', icon: 'message-square', label: 'Share Feedback' },
{ id: 'sign-out', icon: 'log-out', label: 'Sign out' }];

function getInitials(name, fallback) {
  const source = String(name || fallback || '').trim();
  if (!source) return 'JD';
  const parts = source.split(/\s+/).filter(Boolean);
  const first = parts[0] ? parts[0][0] : '';
  const last = parts.length > 1 ? parts[parts.length - 1][0] : '';
  return (first + last || source.slice(0, 2)).toUpperCase();
}

const WORKSPACE_SWITCHER_PAGE_LIMIT = 20;

function getWorkspaceMembershipId(value) {
  const source = value || {};
  return String(source.workspaceId || source.organizationId || source.id || '').trim();
}

function createWorkspaceMembershipsState(workspaceId) {
  return {
    workspaceId: String(workspaceId || ''),
    loaded: false,
    loading: false,
    loadingMore: false,
    error: '',
    availabilityStatus: 'idle',
    availabilityError: '',
    memberships: [],
    page: { offset: 0, limit: WORKSPACE_SWITCHER_PAGE_LIMIT, totalCount: 0, hasMore: false, nextOffset: null }
  };
}

function getWorkspaceSwitcherService() {
  return typeof window !== 'undefined' && window.RankLyxAccountWorkspace ? window.RankLyxAccountWorkspace : null;
}

function normalizeWorkspaceMembershipPageForUi(page) {
  const source = page || {};
  const memberships = Array.isArray(source.memberships)
    ? source.memberships.filter((membership) => membership && membership.workspaceId && membership.name && membership.roleLabel)
    : [];
  const nextOffset = source.nextOffset == null ? null : Number(source.nextOffset);
  return {
    memberships,
    availabilityStatus: source.availabilityStatus === 'ready' ? 'ready' : 'error',
    availabilityError: String(source.availabilityError || ''),
    page: {
      offset: Number(source.offset) || 0,
      limit: Number(source.limit) || WORKSPACE_SWITCHER_PAGE_LIMIT,
      totalCount: Number(source.totalCount) || memberships.length,
      hasMore: source.hasMore === true,
      nextOffset: Number.isFinite(nextOffset) ? nextOffset : null
    }
  };
}

function mergeWorkspaceMembershipsForUi(existing, incoming) {
  const seen = new Set();
  return [...(Array.isArray(existing) ? existing : []), ...(Array.isArray(incoming) ? incoming : [])].filter((membership) => {
    const id = getWorkspaceMembershipId(membership);
    if (!id || seen.has(id)) return false;
    seen.add(id);
    return true;
  });
}

function useWorkspaceMemberships(activeWorkspace, enabled) {
  const activeWorkspaceId = getWorkspaceMembershipId(activeWorkspace);
  const [state, setState] = useState(() => createWorkspaceMembershipsState(activeWorkspaceId));
  const requestRef = useRef(0);
  const inFlightRef = useRef(false);
  const mountedRef = useRef(false);

  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
      requestRef.current += 1;
      inFlightRef.current = false;
    };
  }, []);

  useEffect(() => {
    requestRef.current += 1;
    inFlightRef.current = false;
    setState(createWorkspaceMembershipsState(activeWorkspaceId));
  }, [activeWorkspaceId]);

  const load = (mode) => {
    const loadMode = mode === 'more' ? 'more' : 'initial';
    if (inFlightRef.current) return Promise.resolve(null);
    const service = getWorkspaceSwitcherService();
    if (!service || typeof service.loadCurrentUserWorkspaceMemberships !== 'function') {
      setState((current) => ({ ...current, loading: false, loadingMore: false, error: "We couldn't load your workspaces" }));
      return Promise.resolve(null);
    }
    const append = loadMode === 'more';
    const requestId = requestRef.current + 1;
    const offset = append && state.page && state.page.nextOffset ? state.page.nextOffset : 0;
    requestRef.current = requestId;
    inFlightRef.current = true;
    setState((current) => ({ ...current, loading: !append, loadingMore: append, error: '', availabilityStatus: 'loading', availabilityError: '' }));
    return service.loadCurrentUserWorkspaceMemberships(window.Clerk, {
      limit: WORKSPACE_SWITCHER_PAGE_LIMIT,
      offset
    }).then((page) => {
      if (!mountedRef.current || requestRef.current !== requestId) return page;
      const normalized = normalizeWorkspaceMembershipPageForUi(page);
      setState((current) => ({
        ...current,
        loaded: true,
        loading: false,
        loadingMore: false,
        error: '',
        availabilityStatus: normalized.availabilityStatus,
        availabilityError: normalized.availabilityError,
        memberships: append ? mergeWorkspaceMembershipsForUi(
          service.mergeWorkspaceMembershipAvailability ? service.mergeWorkspaceMembershipAvailability(current.memberships) : current.memberships,
          normalized.memberships
        ) : normalized.memberships,
        page: normalized.page
      }));
      return normalized;
    }).catch(() => {
      if (!mountedRef.current || requestRef.current !== requestId) return null;
      setState((current) => ({ ...current, loaded: false, loading: false, loadingMore: false, error: "We couldn't load your workspaces" }));
      return null;
    }).finally(() => {
      if (requestRef.current === requestId) inFlightRef.current = false;
    });
  };

  useEffect(() => {
    if (!enabled || state.loaded || state.loading || state.error) return undefined;
    load('initial');
    return undefined;
  }, [enabled, state.loaded, state.loading, state.error, activeWorkspaceId]);

  return {
    state,
    loadInitial: () => load('initial'),
    loadMore: () => load('more')
  };
}

function WorkspaceMembershipAvatar({ membership, className }) {
  const source = membership || {};
  const name = source.name || source.workspaceName || 'Workspace';
  return <span className={className} aria-hidden="true">{source.imageUrl ? <img src={source.imageUrl} alt="" /> : getInitials(name, 'WS')}</span>;
}

function WorkspaceMembershipList({ id, variant, workspace, state, switchingId, switchError, onSelect, onCurrent, onRetry, onLoadMore, onSignOut }) {
  const mode = variant === 'settings' ? 'settings' : 'popover';
  const prefix = mode === 'settings' ? 'rl-settings-workspaces' : 'rl-workspace-switcher';
  const currentState = state || createWorkspaceMembershipsState(getWorkspaceMembershipId(workspace));
  const activeWorkspaceId = getWorkspaceMembershipId(workspace);
  const busy = !!switchingId;
  const memberships = Array.isArray(currentState.memberships) ? currentState.memberships : [];
  const availableCount = memberships.filter((membership) => membership && membership.available === true && membership.availabilityStatus === 'available').length;

  if (currentState.loading && !memberships.length) {
    return <p id={id} className={`${prefix}__empty`}>Loading workspaces...</p>;
  }
  if (currentState.error) {
    return <div id={id} className={`${prefix}__alert`} role="alert"><h3>We couldn't load your workspaces</h3><button type="button" className="rl-btn rl-btn--secondary" onClick={onRetry}>Try again</button></div>;
  }
  if (!memberships.length) {
    return <div id={id} className={`${prefix}__alert`}><h3>No workspace available</h3><p>Your ClickLyx account is not connected to a workspace.</p>{onSignOut && <button type="button" className="rl-btn rl-btn--secondary" onClick={onSignOut}>Sign out</button>}</div>;
  }

  return <div id={id} className={`${prefix}__body`}>
    {currentState.availabilityStatus === 'error' && <div className={`${prefix}__alert`} role="alert"><h3>Workspace availability is temporarily unavailable</h3><p>Please try again.</p><button type="button" className="rl-btn rl-btn--secondary" onClick={onRetry}>Try again</button></div>}
    <div className={`${prefix}__list`} role="list">
      {memberships.map((membership) => {
        const workspaceId = getWorkspaceMembershipId(membership);
        const isCurrent = workspaceId && workspaceId === activeWorkspaceId;
        const isAvailable = currentState.availabilityStatus === 'ready' && membership.available === true && membership.availabilityStatus === 'available';
        const secondaryLabel = isAvailable ? membership.roleLabel : currentState.availabilityStatus === 'loading' ? 'Checking availability...' : membership.availabilityStatus === 'unavailable' ? 'Unavailable in Clicklyx' : 'Availability temporarily unavailable';
        const label = switchingId === workspaceId ? 'Switching...' : 'Switch';
        if (mode === 'settings') {
          return <div key={workspaceId || membership.membershipId} className={`${prefix}__row ${isCurrent ? prefix + '__row--current' : ''}`} role="listitem" aria-current={isCurrent ? 'true' : undefined}>
            <WorkspaceMembershipAvatar membership={membership} className={`${prefix}__avatar`} />
            <span className={`${prefix}__meta`}><strong>{membership.name}</strong><small>{secondaryLabel}</small></span>
            {!isAvailable ? <button type="button" className="rl-btn rl-btn--secondary" disabled aria-disabled="true">Unavailable</button> : isCurrent ? <button type="button" className="rl-btn rl-btn--secondary" disabled>Current</button> : <button type="button" className="rl-btn rl-btn--secondary" onClick={() => onSelect && onSelect(membership)} disabled={busy}>{label}</button>}
          </div>;
        }
        return <button key={workspaceId || membership.membershipId} type="button" className={`${prefix}__row ${isCurrent ? prefix + '__row--current' : ''}`} role="listitem" aria-current={isCurrent ? 'true' : undefined} aria-disabled={!isAvailable ? 'true' : undefined} onClick={() => isAvailable && (isCurrent ? onCurrent && onCurrent() : onSelect && onSelect(membership))} disabled={!isAvailable || busy && !isCurrent}>
          <WorkspaceMembershipAvatar membership={membership} className={`${prefix}__avatar`} />
          <span className={`${prefix}__meta`}><strong>{membership.name}</strong><small>{secondaryLabel}</small></span>
          {!isAvailable ? <span className={`${prefix}__action`}>Unavailable</span> : isCurrent ? <span className={`${prefix}__current`}><i data-lucide="check"></i><span>Current</span></span> : <span className={`${prefix}__action`}>{label}</span>}
        </button>;
      })}
    </div>
    {!availableCount && currentState.availabilityStatus === 'ready' && <div className={`${prefix}__alert`}><h3>No Clicklyx Workspaces are currently available for this account.</h3></div>}
    {currentState.page && currentState.page.hasMore && <div className={`${prefix}__load-more`}><button type="button" className="rl-btn rl-btn--secondary" onClick={onLoadMore} disabled={currentState.loadingMore || busy}>{currentState.loadingMore ? 'Loading...' : 'Load more'}</button></div>}
    {switchError && <p className={`${prefix}__error`} role="alert">We couldn't switch workspaces</p>}
  </div>;
}

function useWorkspaceAccessUi() {
  const runtime = window.ClicklyxWorkspaceAccessUi;
  const client = window.ClicklyxWorkspaceAccess;
  const unavailable = {
    status: 'access_unavailable',
    workspaceId: null,
    canMutateWorkspaceContent: false,
    canUseAi: false,
    canAddMembers: false,
    canStartArticleWorkflow: false,
    noticeKind: 'access_unavailable',
    noticeMessage: 'Editing and AI are temporarily unavailable while access is checked. Existing content is still available. Try again.',
    errorCode: 'workspace_access_unavailable'
  };
  const [state, setState] = useState(() => runtime && typeof runtime.readWorkspaceAccessUi === 'function' ? runtime.readWorkspaceAccessUi(client) : unavailable);

  useEffect(() => {
    if (!runtime || typeof runtime.subscribeWorkspaceAccessUi !== 'function') {
      setState(unavailable);
      return undefined;
    }
    return runtime.subscribeWorkspaceAccessUi(client, setState);
  }, []);

  return {
    ...state,
    allows: (capability) => !!(runtime && runtime.allowsWorkspaceAction && runtime.allowsWorkspaceAction(client, state.workspaceId, capability)),
    retry: () => runtime && typeof runtime.refreshWorkspaceAccess === 'function' ? runtime.refreshWorkspaceAccess(client) : Promise.reject(new Error('Workspace access refresh is unavailable.'))
  };
}

function WorkspaceAccessNotice({ access, role, onNavigate }) {
  const [retrying, setRetrying] = useState(false);
  const visible = access && !!access.noticeMessage;
  useEffect(() => {setRetrying(false);}, [access && access.status]);
  useLucide([access && access.status, retrying]);
  if (!visible) return null;

  const retry = () => {
    if (retrying || !access || typeof access.retry !== 'function') return;
    setRetrying(true);
    Promise.resolve(access.retry()).catch(() => {}).finally(() => setRetrying(false));
  };
  const temporary = access.noticeKind === 'access_unavailable';
  const guidance = window.ClicklyxWorkspaceAccessUi.readOnlyGuidance(access, role);
  return <section
    id="rl-workspace-access-notice"
    className={`rl-workspace-access-notice rl-workspace-access-notice--${temporary ? 'temporary' : 'read-only'}`}
    role="status"
    aria-atomic="true"
    data-access-status={access.status}>
    <span className="rl-workspace-access-notice__icon" aria-hidden="true"><i data-lucide={temporary ? 'circle-alert' : 'lock-keyhole'}></i></span>
    <p>{access.noticeMessage}{guidance.memberMessage && <small style={{ display: 'block', marginTop: 4 }}>{guidance.memberMessage}</small>}</p>
    {guidance.showBilling && typeof onNavigate === 'function' && <button type="button" className="rl-btn rl-btn--secondary" onClick={() => onNavigate('settings', { section: 'billing' })}>Billing &amp; credits</button>}
    {temporary && <button type="button" className="rl-btn rl-btn--secondary rl-workspace-access-notice__retry" onClick={retry} disabled={retrying}>{retrying ? 'Checking...' : 'Try again'}</button>}
  </section>;
}

function Sidebar({ active, onNavigate, user, workspace, creditState, workspaceAccess, websites, websiteId }) {
  const mainItems = [
  { id: 'dashboard', icon: 'layout-grid', label: 'Home' },
  { id: 'calendar', icon: 'calendar', label: 'Calendar' },
  { id: 'articles', icon: 'file-text', label: 'Articles' }];

  const createItems = [
  { id: 'ai-writer', icon: 'sparkles', label: 'AI Writer', capability: 'article' },
  { id: 'ai-chat', icon: 'message-circle', label: 'AI Chat', capability: 'ai' }];

  const knowledgeChildren = [
  { id: 'brand-profile', label: 'Brand Profile' },
  { id: 'product-knowledge', label: 'Product Knowledge' },
  { id: 'audience-icp', label: 'ICP Knowledge' },
  { id: 'brand-voice', label: 'Brand Voice' }];
  const knowledgeActive = knowledgeChildren.some((c) => c.id === active);

  const [menuOpen, setMenuOpen] = useState(false);
  const [knowledgeOpen, setKnowledgeOpen] = useState(knowledgeActive);
  const [workspaceSwitcherOpen, setWorkspaceSwitcherOpen] = useState(false);
  const [workspaceSwitchingId, setWorkspaceSwitchingId] = useState('');
  const [workspaceSwitchError, setWorkspaceSwitchError] = useState('');
  const workspaceSwitcherTriggerRef = useRef(null);
  const workspaceSwitcherRef = useRef(null);
  const workspaceMemberships = useWorkspaceMemberships(workspace, workspaceSwitcherOpen);
  const displayName = (user && (user.fullName || user.displayName || user.name)) || 'Account';
  const displayEmail = (user && user.email) || '';
  const avatarDataUrl = user && user.avatarDataUrl;
  const initials = getInitials(displayName, displayEmail);
  const savedWorkspace = workspace || {};
  const hasSavedWorkspace = !!(savedWorkspace.id || savedWorkspace.organizationId || savedWorkspace.website || savedWorkspace.websiteUrl || savedWorkspace.hasImage === true || savedWorkspace.name && savedWorkspace.name !== 'Workspace');
  const workspaceDisplayName = hasSavedWorkspace && savedWorkspace.name ? String(savedWorkspace.name) : 'RankLyx';
  const rawSidebarWorkspaceLogoUrl = savedWorkspace.imageUrl || savedWorkspace.logoDataUrl || savedWorkspace.logoUrl || '';
  const sidebarWorkspaceLogoUrl = savedWorkspace.hasImage === true && !!rawSidebarWorkspaceLogoUrl ? rawSidebarWorkspaceLogoUrl : '';
  const commercialRuntime = window.RankLyxWorkspaceCommercial;
  const creditFooter = commercialRuntime && typeof commercialRuntime.creditFooterText === 'function' ? commercialRuntime.creditFooterText(creditState) : 'Articles unavailable';

  const closeWorkspaceSwitcher = (returnFocus) => {
    setWorkspaceSwitcherOpen(false);
    setWorkspaceSwitchError('');
    if (returnFocus && workspaceSwitcherTriggerRef.current) workspaceSwitcherTriggerRef.current.focus();
  };

  const handleSidebarWorkspaceSwitch = (membership) => {
    const workspaceId = getWorkspaceMembershipId(membership);
    if (!workspaceId || workspaceSwitchingId) return;
    if (workspaceId === getWorkspaceMembershipId(workspace)) {
      closeWorkspaceSwitcher(false);
      return;
    }
    const service = getWorkspaceSwitcherService();
    if (!service || typeof service.switchActiveWorkspace !== 'function') {
      setWorkspaceSwitchError("We couldn't switch workspaces");
      return;
    }
    setWorkspaceSwitchingId(workspaceId);
    setWorkspaceSwitchError('');
    service.switchActiveWorkspace(window.Clerk, workspaceMemberships.state.memberships, workspaceId, { reload: true, reloadPath: '/' }).then(() => {
      setWorkspaceSwitcherOpen(false);
    }).catch(() => {
      setWorkspaceSwitchError("We couldn't switch workspaces");
    }).finally(() => {
      setWorkspaceSwitchingId('');
    });
  };

  const handleSidebarSignOut = () => {
    if (window.RankLyxAuth && typeof window.RankLyxAuth.signOut === 'function') window.RankLyxAuth.signOut();
  };

  /* Keep the Knowledge group open whenever one of its pages is active. */
  useEffect(() => {if (knowledgeActive) setKnowledgeOpen(true);}, [knowledgeActive]);

  useLucide([active, menuOpen, knowledgeOpen, workspaceSwitcherOpen, workspaceMemberships.state, workspaceSwitchingId, workspaceSwitchError]);
  useEffect(() => {
    const onKey = (e) => {if (e.key === 'Escape') setMenuOpen(false);};
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, []);

  useEffect(() => {
    if (!workspaceSwitcherOpen) return undefined;
    const onPointerDown = (event) => {
      const target = event && event.target;
      if (!target) return;
      if (workspaceSwitcherRef.current && workspaceSwitcherRef.current.contains(target)) return;
      if (workspaceSwitcherTriggerRef.current && workspaceSwitcherTriggerRef.current.contains(target)) return;
      closeWorkspaceSwitcher(false);
    };
    const onKeyDown = (event) => {
      if (event.key === 'Escape') {
        event.preventDefault();
        closeWorkspaceSwitcher(true);
      }
    };
    document.addEventListener('mousedown', onPointerDown);
    document.addEventListener('touchstart', onPointerDown);
    document.addEventListener('keydown', onKeyDown);
    return () => {
      document.removeEventListener('mousedown', onPointerDown);
      document.removeEventListener('touchstart', onPointerDown);
      document.removeEventListener('keydown', onKeyDown);
    };
  }, [workspaceSwitcherOpen]);

  const renderNavItem = (it) => {
    const blocked = it.capability === 'article' ? !(workspaceAccess && workspaceAccess.canStartArticleWorkflow === true) :
      it.capability === 'ai' ? !(workspaceAccess && workspaceAccess.canUseAi === true) : false;
    const noticeVisible = active === 'dashboard' || active === 'articles' || active === 'ai-writer';
    const describedBy = blocked && noticeVisible && workspaceAccess && workspaceAccess.noticeMessage ? 'rl-workspace-access-notice' : undefined;
    return <button
      key={it.id}
      type="button"
      className={`rl-nav__item ${active === it.id ? 'rl-nav__item--active' : ''}`}
      onClick={() => !blocked && onNavigate && onNavigate(it.id)}
      disabled={blocked}
      aria-describedby={describedBy}
      aria-current={active === it.id ? 'page' : undefined}>
      <i data-lucide={it.icon}></i>
      <span>{it.label}</span>
    </button>;
  };

  const handleProfileMenuClick = (item) => {
    setMenuOpen(false);
    if (item && item.id === 'sign-out' && window.RankLyxAuth && typeof window.RankLyxAuth.signOut === 'function') {
      window.RankLyxAuth.signOut();
      return;
    }
    if (item && item.id === 'settings' && onNavigate) onNavigate('settings', { section: 'profile' });
    if (item && item.id === 'credits' && onNavigate) onNavigate('settings', { section: 'billing' });
  };

  return (
    <aside className="rl-side" data-screen-label="Sidebar" style={{ opacity: "1", backgroundColor: "rgba(238, 240, 242, 0.706)" }}>
      <div className="rl-side__workspace-switcher">
        <button
          ref={workspaceSwitcherTriggerRef}
          type="button"
          className={`rl-side__brand rl-side__brand--switcher ${workspaceSwitcherOpen ? 'rl-side__brand--open' : ''}`}
          title={workspaceDisplayName}
          aria-label={'Switch workspace. Current workspace: ' + workspaceDisplayName}
          aria-haspopup="dialog"
          aria-expanded={workspaceSwitcherOpen}
          aria-controls="rl-sidebar-workspace-switcher"
          onClick={() => { setMenuOpen(false); setWorkspaceSwitcherOpen((open) => !open); }}>
          {sidebarWorkspaceLogoUrl ? <img className="rl-side__brand-logo" src={sidebarWorkspaceLogoUrl} alt="" /> : <img className="rl-side__brand-logo" src="assets/glyph.svg" alt="" />}
          <div className="wm rl-side__workspace-name">{workspaceDisplayName}</div>
          <i data-lucide="chevron-down" className={`rl-side__workspace-caret ${workspaceSwitcherOpen ? 'rl-side__workspace-caret--open' : ''}`}></i>
        </button>
        {workspaceSwitcherOpen && <div ref={workspaceSwitcherRef} id="rl-sidebar-workspace-switcher" className="rl-workspace-switcher" role="dialog" aria-modal="false" aria-labelledby="rl-sidebar-workspace-switcher-title">
          <div className="rl-workspace-switcher__head">
            <h2 id="rl-sidebar-workspace-switcher-title">Switch workspace</h2>
          </div>
          <WorkspaceMembershipList
            id="rl-sidebar-workspace-switcher-list"
            variant="popover"
            workspace={workspace}
            state={workspaceMemberships.state}
            switchingId={workspaceSwitchingId}
            switchError={workspaceSwitchError}
            onSelect={handleSidebarWorkspaceSwitch}
            onCurrent={() => closeWorkspaceSwitcher(false)}
            onRetry={workspaceMemberships.loadInitial}
            onLoadMore={workspaceMemberships.loadMore}
            onSignOut={handleSidebarSignOut} />
        </div>}
      </div>

      <nav className="rl-nav" aria-label="Primary navigation">
        <div className="rl-nav__group">
          <div className="rl-nav__label">Main</div>
          {mainItems.map(renderNavItem)}
        </div>

        <div className="rl-nav__group">
          <div className="rl-nav__label">Create</div>
          {createItems.map(renderNavItem)}
        </div>

        <div className={`rl-nav__group rl-nav__group--knowledge ${knowledgeActive ? 'rl-nav__group--active' : ''}`}>
          <div className="rl-nav__label">Brand</div>
          {websites ? <window.ClicklyxWebsitesUI.WebsitesSidebar state={websites} active={active} websiteId={websiteId} onNavigate={onNavigate} /> : <React.Fragment>
          <button
            type="button"
            className={`rl-nav__item rl-nav__parent ${knowledgeActive ? 'rl-nav__item--soft' : ''}`}
            aria-expanded={knowledgeOpen}
            onClick={() => setKnowledgeOpen((o) => !o)}>
            <i data-lucide="book-open"></i>
            <span>Knowledge</span>
            <i data-lucide="chevron-down" className={`rl-nav__chevron ${knowledgeOpen ? 'rl-nav__chevron--open' : ''}`}></i>
          </button>
          {knowledgeOpen &&
          <div className="rl-nav__sub" role="group" aria-label="Knowledge">
            {knowledgeChildren.map((c) =>
            <button
              key={c.id}
              className={`rl-nav__child ${active === c.id ? 'rl-nav__child--active' : ''}`}
              onClick={() => onNavigate && onNavigate(c.id)}
              aria-current={active === c.id ? 'page' : undefined}>
              <span className="rl-nav__childdot"></span>
              <span>{c.label}</span>
            </button>
            )}
          </div>}
          </React.Fragment>}
        </div>
      </nav>

      <div className="rl-side__foot">
        {menuOpen && <div className="rl-umenu__scrim" onClick={() => setMenuOpen(false)}></div>}
        <div className={`rl-umenu ${menuOpen ? 'rl-umenu--open' : ''}`} role="menu" aria-hidden={!menuOpen}>
          <div className="rl-umenu__head">
            <div className="rl-umenu__av">{avatarDataUrl ? <img src={avatarDataUrl} alt="" /> : initials}</div>
            <div className="rl-umenu__id">
              <div className="rl-umenu__name">{displayName}</div>
              {displayEmail && <div className="rl-umenu__email">{displayEmail}</div>}
            </div>
          </div>
          {PROFILE_MENU.map((m) =>
          <button key={m.label} type="button" className="rl-umenu__item" role="menuitem" onClick={() => handleProfileMenuClick(m)}>
            <i data-lucide={m.icon}></i><span>{m.label}</span>
          </button>
          )}
        </div>
        <button
          type="button"
          className={`rl-user ${menuOpen ? 'rl-user--open' : ''}`}
          aria-haspopup="true"
          aria-expanded={menuOpen}
          onClick={() => setMenuOpen((v) => !v)}>
          <div className="rl-user__av">{avatarDataUrl ? <img src={avatarDataUrl} alt="" /> : initials}</div>
          <div className="rl-user__meta">
            <div className="rl-user__name">{displayName}</div>
            <div className="rl-user__plan">{creditFooter}</div>
          </div>
          <i data-lucide="chevrons-up-down" className="rl-user__caret" style={{ width: 16, height: 16 }}></i>
        </button>
      </div>
    </aside>);

}

/* ------------------------------------------------------------------ */
/* Top bar inside the workspace */
function TopBar({ active, onNavigate, workspaceAccess }) {
  useLucide([active]);
  const canStartArticle = workspaceAccess && workspaceAccess.canStartArticleWorkflow === true;
  const noticeVisible = active === 'dashboard' || active === 'articles' || active === 'ai-writer';
  const accessDescriptionId = !canStartArticle && noticeVisible && workspaceAccess && workspaceAccess.noticeMessage ? 'rl-workspace-access-notice' : undefined;
  const isWebsites = active === 'websites' || active === 'website-knowledge';
  const isDash = active === 'dashboard';
  const isCal = active === 'calendar';
  const isArticles = active === 'articles';
  const isSettings = active === 'settings';
  const isBrand = active === 'brand-profile';
  const isProduct = active === 'product-knowledge';
  const isAudience = active === 'audience-icp';
  const isVoice = active === 'brand-voice';
  return (
    <div className="rl-topbar">
      <div className="rl-crumbs">
        {isWebsites ? <span className="rl-crumbs__current">Websites</span> : isDash ?
        <span className="rl-crumbs__current">Home</span> :
        isCal ?
        <span className="rl-crumbs__current">Calendar</span> :
        isArticles ?
        <span className="rl-crumbs__current">Articles</span> :
        isSettings ?
        <span className="rl-crumbs__current">Settings</span> :
        isBrand ?
        <>
          <span>Knowledge</span>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6"></path></svg>
          <span className="rl-crumbs__current">Brand Profile</span>
        </> :
        isProduct ?
        <>
          <span>Knowledge</span>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6"></path></svg>
          <span className="rl-crumbs__current">Product Knowledge</span>
        </> :
        isAudience ?
        <>
          <span>Knowledge</span>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6"></path></svg>
          <span className="rl-crumbs__current">ICP Knowledge</span>
        </> :
        isVoice ?
        <>
          <span>Knowledge</span>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6"></path></svg>
          <span className="rl-crumbs__current">Brand Voice</span>
        </> :
        <>
          <span>AI Writer</span>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6"></path></svg>
          <span className="rl-crumbs__current">New article</span>
        </>}
      </div>
      <div className="rl-topbar__right">
        <button type="button" className="rl-btn rl-btn--primary rl-topbar__cta" onClick={() => canStartArticle && onNavigate && onNavigate('ai-writer')} disabled={!canStartArticle} aria-describedby={accessDescriptionId} style={{ borderRadius: "8px", fontSize: "13px", gap: "3px", padding: "5px" }}>
          <i data-lucide="plus"></i><span>New article</span>
        </button>
        <button className="rl-iconbtn" aria-label="Search">
          <i data-lucide="search"></i>
        </button>
        <button className="rl-iconbtn" aria-label="Notifications">
          <i data-lucide="bell"></i>
        </button>
        <button className="rl-iconbtn" aria-label="Help">
          <i data-lucide="circle-help"></i>
        </button>
      </div>
    </div>);

}

/* ------------------------------------------------------------------ */
/* Step progress indicator */
function Stepper({ step }) {
  const steps = [
  { id: 1, label: 'Brief' },
  { id: 2, label: 'Outline' },
  { id: 3, label: 'Draft' },
  { id: 4, label: 'Publish' }];

  return (
    <div className="rl-tabs" role="list" aria-label="Workflow progress">
      {steps.map((s) =>
      <span
        key={s.id}
        role="listitem"
        aria-current={s.id === step ? 'step' : undefined}
        className={'rl-tab ' + (s.id === step ? 'rl-tab--active' : '')}>
          {s.label}
        </span>
      )}
    </div>);

}

/* ------------------------------------------------------------------ */
/* Field building blocks */
function Field({ label, optional, hint, children, full }) {
  return (
    <div className={`rl-field ${full ? 'rl-field--full' : ''}`}>
      <label className="rl-field__label">
        <span>{label}</span>
        {optional ?
        <span className="opt">Optional</span> :

        <React.Fragment>
          <span className="req" aria-hidden="true">*</span>
          <span className="rl-sr-only">Required</span>
        </React.Fragment>
        }
      </label>
      {hint && <div className="rl-field__hint">{hint}</div>}
      {children}
    </div>);

}

function TextInput({ icon, value, onChange, placeholder, name, readOnly = false }) {
  return (
    <div className="rl-input-wrap">
      {icon &&
      <span className="lead"><i data-lucide={icon}></i></span>
      }
      <input
        className={`rl-input ${icon ? 'rl-input--icon' : ''}`}
        type="text"
        name={name}
        value={value}
        readOnly={readOnly}
        aria-readonly={readOnly ? 'true' : undefined}
        onChange={(e) => {if (!readOnly) onChange(e.target.value);}}
        placeholder={placeholder}
        autoComplete="off" />
      
    </div>);

}

/* Tone of voice - text field with a dropdown of suggestions on focus/click */
function ToneSelect({ value, onChange, placeholder, options, disabled = false }) {
  const [open, setOpen] = useState(false);
  const wrapRef = useRef(null);

  /* parse the comma-separated value into a set of trimmed tokens */
  const selected = useMemo(
    () => value.split(',').map((s) => s.trim()).filter(Boolean),
    [value]
  );
  const has = (t) => selected.some((s) => s.toLowerCase() === t.toLowerCase());

  const toggle = (t) => {
    if (disabled) return;
    if (has(t)) {
      onChange(selected.filter((s) => s.toLowerCase() !== t.toLowerCase()).join(', '));
    } else {
      onChange([...selected, t].join(', '));
    }
  };

  /* close on outside click / Escape */
  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);};
    const onKey = (e) => {if (e.key === 'Escape') setOpen(false);};
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {document.removeEventListener('mousedown', onDoc);document.removeEventListener('keydown', onKey);};
  }, [open]);

  useEffect(() => {if (disabled) setOpen(false);}, [disabled]);

  useLucide([open, value]);

  return (
    <div className="rl-select-wrap" ref={wrapRef}>
      <div className="rl-input-wrap">
        <input
          className="rl-input rl-input--select"
          type="text"
          value={value}
          readOnly={disabled}
          aria-readonly={disabled ? 'true' : undefined}
          onChange={(e) => {if (!disabled) onChange(e.target.value);}}
          onFocus={() => {if (!disabled) setOpen(true);}}
          onClick={() => {if (!disabled) setOpen(true);}}
          placeholder={placeholder}
          autoComplete="off" style={{ borderRadius: "10px", borderWidth: "2px 2px 2px 1px" }} />
        
        <button
          type="button"
          className={`rl-caret ${open ? 'rl-caret--open' : ''}`}
          aria-label="Toggle tone suggestions"
          disabled={disabled}
          onClick={(e) => {e.preventDefault();if (!disabled) setOpen((o) => !o);}}
          tabIndex={-1}>
          
          <i data-lucide="chevron-down"></i>
        </button>
      </div>

      {open &&
      <div className="rl-menu" role="listbox">
          <div className="rl-menu__hd">Suggested tones · tap to combine</div>
          {options.map((t) =>
        <button
          key={t}
          type="button"
          role="option"
          aria-selected={has(t)}
          className={`rl-menu__item ${has(t) ? 'rl-menu__item--on' : ''}`}
          onClick={() => toggle(t)}>
          
              <span className="rl-menu__check">
                {has(t) && <i data-lucide="check"></i>}
              </span>
              <span>{t}</span>
            </button>
        )}
        </div>
      }
    </div>);

}

/* ------------------------------------------------------------------ */
/* Chips input - comma-separated keywords shown as removable chips */
function ChipsInput({ value, onChange, placeholder, disabled = false }) {
  const [draft, setDraft] = useState('');
  const chips = value.split(',').map((s) => s.trim()).filter(Boolean);

  const commit = (raw) => {
    if (disabled) return;
    const next = raw.split(',').map((s) => s.trim()).filter(Boolean);
    const merged = [...chips];
    next.forEach((n) => {if (!merged.some((c) => c.toLowerCase() === n.toLowerCase())) merged.push(n);});
    onChange(merged.join(', '));
    setDraft('');
  };

  const remove = (i) => {if (!disabled) onChange(chips.filter((_, idx) => idx !== i).join(', '));};

  const onKeyDown = (e) => {
    if (disabled) return;
    if (e.key === 'Enter' || e.key === ',') {
      e.preventDefault();
      if (draft.trim()) commit(draft);
    } else if (e.key === 'Backspace' && !draft && chips.length) {
      remove(chips.length - 1);
    }
  };

  useLucide([value]);

  return (
    <div className="rl-chips" aria-readonly={disabled ? 'true' : undefined} onClick={(e) => {if (!disabled) e.currentTarget.querySelector('input').focus();}} style={{ borderWidth: "2px" }}>
      {chips.map((c, i) =>
      <span className="rl-chip" key={i}>
          <span>{c}</span>
          <button type="button" aria-label={`Remove ${c}`} disabled={disabled} onClick={(e) => {e.stopPropagation();remove(i);}}>
            <i data-lucide="x"></i>
          </button>
        </span>
      )}
      <input
        className="rl-chips__input"
        type="text"
        value={draft}
        disabled={disabled}
        onChange={(e) => {if (!disabled) setDraft(e.target.value);}}
        onKeyDown={onKeyDown}
        onBlur={() => draft.trim() && commit(draft)}
        placeholder={chips.length ? '' : placeholder}
        autoComplete="off" />
      
    </div>);

}

/* ------------------------------------------------------------------ */
/* Single-select dropdown */
function SelectInput({ value, onChange, placeholder, options, disabled = false,
  id, label, labelledBy, describedBy, invalid, required, icon, onOpen, className = '' }) {
  const [open, setOpen] = useState(false);
  const wrapRef = useRef(null);
  const [menuStyle, setMenuStyle] = useState(undefined);
  const triggerRef = useRef(null), optionRefs = useRef([]), openingIndex = useRef(null), typed = useRef({text:'',at:0});
  const normalizedOptions = (options || []).map((opt) =>
  typeof opt === 'string' ? { label: opt, value: opt } : opt
  );
  const selectedOption = normalizedOptions.find((opt) => opt.value === value);
  const displayValue = selectedOption ? selectedOption.label : value;
  const enabledIndexes = normalizedOptions.map((opt,index) => opt.disabled ? -1 : index).filter(index => index >= 0);
  const close = () => {setOpen(false);if(id)triggerRef.current?.focus();};
  const focusOption = index => optionRefs.current[index]?.focus();
  const show = index => {
    if(disabled)return;
    // Keep Website menus usable beside the existing narrow mobile page shell.
    if(id && window.innerWidth <= 640 && triggerRef.current){
      const rect=triggerRef.current.getBoundingClientRect(),width=Math.min(240,window.innerWidth-32);
      const above=window.innerHeight-rect.bottom<264 && rect.top>window.innerHeight-rect.bottom;
      setMenuStyle({position:'fixed',left:Math.max(16,Math.min(rect.right-width,window.innerWidth-width-16)),right:'auto',width,maxWidth:width,
        top:above?'auto':rect.bottom+6,bottom:above?window.innerHeight-rect.top+6:'auto',
        maxHeight:Math.max(80,Math.min(264,above?rect.top-22:window.innerHeight-rect.bottom-22))});
    }else setMenuStyle(undefined);
    openingIndex.current=index;onOpen?.();setOpen(true);
  };
  // Website controls opt in via id; existing Post type presentation/behavior stays intact.
  const keyboard = (event, index = -1) => {
    if(disabled)return;
    if(event.key === 'Escape' && open){event.preventDefault();event.stopPropagation();close();return;}
    if(event.key === 'Tab' && open){close();return;}
    if(['ArrowDown','ArrowUp','Home','End'].includes(event.key)){
      event.preventDefault();const position=enabledIndexes.indexOf(index),last=enabledIndexes.length-1;
      const next=event.key==='Home'?enabledIndexes[0]:event.key==='End'?enabledIndexes[last]:
        event.key==='ArrowDown'?enabledIndexes[(position+1)%enabledIndexes.length]:enabledIndexes[position<=0?last:position-1];
      if(open)focusOption(next);else show(next);return;
    }
    if(open && event.key.length===1 && event.key!==' ' && !event.ctrlKey && !event.metaKey && !event.altKey){
      event.preventDefault();const now=Date.now();typed.current={text:(now-typed.current.at<700?typed.current.text:'')+event.key.toLowerCase(),at:now};
      const next=enabledIndexes.find(i=>String(normalizedOptions[i].label).toLowerCase().startsWith(typed.current.text));if(next!==undefined)focusOption(next);
    }
  };
  useEffect(() => {
    if(!open || !id)return;
    const selected=normalizedOptions.findIndex(opt=>opt.value===value && !opt.disabled);
    focusOption(openingIndex.current ?? (selected>=0?selected:enabledIndexes[0]));openingIndex.current=null;
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onDoc = (e) => {if (wrapRef.current && !wrapRef.current.contains(e.target)) setOpen(false);};
    const onKey = (e) => {if (e.key === 'Escape') setOpen(false);};
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {document.removeEventListener('mousedown', onDoc);document.removeEventListener('keydown', onKey);};
  }, [open]);

  useEffect(() => {if (disabled) setOpen(false);}, [disabled]);

  useLucide([open, value]);

  return (
    <div className={`rl-select-wrap ${id ? 'c5-website-select' : ''} ${className}`} ref={wrapRef}
      onBlur={id ? event=>{if(!event.currentTarget.contains(event.relatedTarget))setOpen(false);} : undefined}>
      <button
        type="button"
        ref={triggerRef} id={id} value={value || ''} role={id ? 'combobox' : undefined}
        className={icon ? `rl-articles-tool ${open || value ? 'rl-articles-tool--active' : ''}` : `rl-input rl-input--select rl-select-trigger ${displayValue && !(required && !value) ? '' : 'rl-select-trigger--empty'}`}
        aria-label={label} aria-labelledby={labelledBy} aria-describedby={describedBy} aria-invalid={invalid} aria-required={required}
        aria-controls={open && id ? id+'-listbox' : undefined}
        aria-haspopup="listbox"
        aria-expanded={open}
        disabled={disabled}
        onKeyDown={id ? event=>keyboard(event) : undefined}
        onClick={() => {if (!disabled){if(open)setOpen(false);else show(null);}}}>
        {icon ? <i data-lucide={icon} aria-hidden="true" /> : <React.Fragment><span>{displayValue || placeholder}</span>
        <span className={`rl-caret ${open ? 'rl-caret--open' : ''}`} aria-hidden="true">
          <i data-lucide="chevron-down"></i>
        </span></React.Fragment>}
      </button>

      {open &&
      <div className="rl-menu" role="listbox" style={menuStyle} id={id ? id+'-listbox' : undefined} aria-label={label} aria-labelledby={labelledBy}>
          {normalizedOptions.map((opt,index) =>
        <button
          key={opt.value}
          ref={node=>{optionRefs.current[index]=node;}} value={opt.value}
          type="button"
          role="option"
          disabled={!!opt.disabled} aria-disabled={opt.disabled || undefined} tabIndex={id ? -1 : undefined}
          aria-selected={value === opt.value}
          className={`rl-menu__item ${value === opt.value ? 'rl-menu__item--on' : ''}`}
          onKeyDown={id ? event=>keyboard(event,index) : undefined}
          onClick={() => {if (!disabled && !opt.disabled){onChange(opt.value, opt);close();}}}>
            
              <span className="rl-menu__check rl-menu__check--radio">
                {value === opt.value && <i data-lucide="check"></i>}
              </span>
              <span>{opt.label}</span>
            </button>
        )}
        </div>
      }
    </div>);

}

/* ------------------------------------------------------------------ */
/* Live brief summary - read-only preview of the form state */
const DEFAULT_BRAND_VOICE_LABEL = 'Default (conversational and authoritative)';
const DEFAULT_BRAND_VOICE_TONE = 'Conversational and authoritative';

function createBriefFormDefaults() {
  return {
    topic: '',
    keyword: '',
    secondaryKeywords: '',
    postType: '',
    goal: '',
    tone: DEFAULT_BRAND_VOICE_TONE,
    brandVoiceId: 'default',
    selectedBrandVoiceId: 'default',
    selectedBrandVoiceName: DEFAULT_BRAND_VOICE_LABEL,
    targetAudienceId: '',
    selectedIcpId: '',
    selectedIcpName: '',
    audience: '',
    notes: ''
  };
}

function createBriefKnowledgeSelectionDefaults() {
  return {
    brandVoice: { kind: 'default' },
    icp: null
  };
}
function BriefSummary({ form, cardRef }) {
  const [notesOpen, setNotesOpen] = useState(false);
  const brandVoiceLabel = form.selectedBrandVoiceName || (form.brandVoiceId === 'default' || !form.brandVoiceId ?
  DEFAULT_BRAND_VOICE_LABEL :
  form.brandVoiceId);
  const targetAudienceLabel = form.selectedIcpName || (form.targetAudienceId === 'create-icp' ?
  'Create ideal customer profile' :
  form.audience || '');
  const rows = [
  { key: 'topic', label: 'Topic' },
  { key: 'keyword', label: 'Primary keyword' },
  { key: 'postType', label: 'Post type', emptyText: 'Not selected yet' },
  { key: 'brandVoiceId', label: 'Brand voice', value: brandVoiceLabel },
  { key: 'targetAudienceId', label: 'Target audience', value: targetAudienceLabel, emptyText: 'No ICP selected yet' },
  { key: 'notes', label: 'Additional information' }];

  const filled = rows.filter((r) => form[r.key].trim().length > 0).length;

  useLucide([form, notesOpen]);

  return (
    <div className="rl-summary-wrap">
      <div className="rl-summary__hd">
        <span className="rl-summary__heading">Brief summary</span>
        <span className="rl-summary__count">{filled}/{rows.length}</span>
      </div>

      <aside ref={cardRef} className="rl-summary" aria-label="Brief summary">
        <dl className="rl-summary__list">
          {rows.map((r) => {
            const val = String(r.value != null ? r.value : form[r.key] || '').trim();
            const isNotes = r.key === 'notes';
            const longNotes = isNotes && val.length > 120;
            return (
              <div className="rl-summary__row" key={r.key}>
                <dt>{r.label}</dt>
                {val ?
                <dd className={isNotes && notesOpen ? 'rl-summary__dd rl-summary__dd--full' : 'rl-summary__dd'}>
                    {val}
                  </dd> :

                <dd className="rl-summary__dd rl-summary__empty">{r.emptyText || 'Not added yet'}</dd>
                }
                {longNotes &&
                <button
                  type="button"
                  className="rl-summary__more"
                  onClick={() => setNotesOpen((o) => !o)}>
                    {notesOpen ? 'Show less' : 'View full notes'}
                  </button>
                }
              </div>);

          })}
        </dl>
      </aside>
    </div>);

}

/* ------------------------------------------------------------------ */
/* The Brief screen */
function BriefScreen({ prefill, workflow, onCreateKnowledge, briefRestoreRequest, knowledgeSelectionRequest, workspaceAccess, onSafeNavigate, websites }) {
  const c5Enabled = !!websites;
  const websiteClient = window.ClicklyxWebsites;
  const [websiteError, setWebsiteError] = useState('');
  const briefWebsiteRef = useRef({version:0, origin:null});
  const WF = window.RankLyxArticleWorkflow || null;
  const initialWorkflow = workflow || { kind: 'new-cloud' };
  const initialCloudIdentity = WF && initialWorkflow.kind === 'cloud' && initialWorkflow.articleId ?
    { kind: 'cloud', articleId: initialWorkflow.articleId } :
    null;
  const isLegacyWorkflow = initialWorkflow.kind === 'legacy';
  const [form, setForm] = useState(() => ({...createBriefFormDefaults(), ...(c5Enabled ? {websiteId:''} : {})}));
  const formRef = useRef(form);
  formRef.current = form;
  const [toast, setToast] = useState(null);
  const [step, setStep] = useState(1);
  const [outline, setOutline] = useState(null);
  /* Prompt-4: Create-Outline async workflow state. */
  const [creating, setCreating] = useState(false);
  const [createStatus, setCreateStatus] = useState(null);
  const [outlineMeta, setOutlineMeta] = useState(null);
  const [cloudIdentity, setCloudIdentity] = useState(initialCloudIdentity);
  const [cloudKnowledgeSnapshot, setCloudKnowledgeSnapshot] = useState(null);
  const [cloudLoadState, setCloudLoadState] = useState(initialCloudIdentity ? 'loading' : 'idle');
  const [cloudLoadError, setCloudLoadError] = useState('');
  const [outlineSaveState, setOutlineSaveState] = useState('idle');
  const [outlineSaveError, setOutlineSaveError] = useState('');
  const [cloudResearch, setCloudResearch] = useState([]);
  const [cloudDraft, setCloudDraft] = useState(null);
  const [briefKnowledge, setBriefKnowledge] = useState({
    status: 'loading',
    brandVoices: [],
    icps: [],
    error: ''
  });
  const [selectedKnowledge, setSelectedKnowledge] = useState(createBriefKnowledgeSelectionDefaults);
  const [knowledgeActionError, setKnowledgeActionError] = useState('');
  const cloudControllerRef = useRef(null);
  const briefKnowledgeControllerRef = useRef(null);
  const briefKnowledgeRequestRef = useRef(0);
  const createInFlightRef = useRef(false);
  const cloudOutlineSaveRequestRef = useRef(0);
  const cloudOutlineSaveInFlightRef = useRef(false);
  const lastSavedCloudOutlineRef = useRef(null);
  const briefAutosaveSuppressedRef = useRef(null);
  const outlineAutosaveSuppressedRef = useRef(null);
  const accessRef = useRef(workspaceAccess);
  accessRef.current = workspaceAccess;

  const OutlineScreen = window.OutlineScreen;
  const isCloudWorkflow = !isLegacyWorkflow;
  const canMutateBrief = !!(workspaceAccess && workspaceAccess.canMutateWorkspaceContent === true);
  const canGenerateBrief = canMutateBrief && !!(workspaceAccess && workspaceAccess.canUseAi === true);
  const accessDescriptionId = workspaceAccess && workspaceAccess.noticeMessage ? 'rl-workspace-access-notice' : undefined;
  const hadFullAccessRef = useRef(workspaceAccess && workspaceAccess.status === 'full');
  if (workspaceAccess && workspaceAccess.status === 'full') hadFullAccessRef.current = true;
  const canMutateNow = () => !!(accessRef.current && accessRef.current.canMutateWorkspaceContent === true);
  const canGenerateNow = () => canMutateNow() && !!(accessRef.current && accessRef.current.canUseAi === true);

  const getCloudController = () => {
    if (!cloudControllerRef.current && WF && typeof WF.createCloudBriefOutlineController === 'function') {
      cloudControllerRef.current = WF.createCloudBriefOutlineController();
    }
    return cloudControllerRef.current;
  };

  const getBriefKnowledgeController = () => {
    if (!briefKnowledgeControllerRef.current && WF && typeof WF.createBriefKnowledgeController === 'function') {
      briefKnowledgeControllerRef.current = WF.createBriefKnowledgeController({
        cloudClient: window.RankLyxCloudKnowledge,
        getOrigin: () => c5Enabled ? briefWebsiteRef.current.origin : undefined
      });
    }
    return briefKnowledgeControllerRef.current;
  };

  const clearCloudWorkflowIdentity = () => {
    setCloudIdentity(null);
    setCloudKnowledgeSnapshot(null);
    try {
      if (WF && typeof WF.writeCloudArticleRoute === 'function') WF.writeCloudArticleRoute('');
    } catch (e) {}
  };

  const cloudDraftHasEditorHtml = (draft) => !!(draft && typeof draft === 'object' && typeof draft.html === 'string' && draft.html.trim());

  const replaceWithCloudEditor = (articleId) => {
    const cloudClient = window.RankLyxCloudArticles;
    let href = '';
    try {
      href = WF && typeof WF.buildCloudEditorUrl === 'function'
        ? WF.buildCloudEditorUrl(articleId, cloudClient)
        : '';
    } catch (e) { href = ''; }
    if (!href) return false;
    if (window.location && typeof window.location.replace === 'function') window.location.replace(href);
    else window.location.href = href;
    return true;
  };

  const resetStaleCloudWorkflow = (message) => {
    clearCloudWorkflowIdentity();
    setOutline(null);
    setOutlineMeta(null);
    lastSavedCloudOutlineRef.current = null;
    setCloudResearch([]);
    setCloudDraft(null);
    setOutlineSaveState('idle');
    setOutlineSaveError('');
    setStep(1);
    if (message) submit(message, false, 'error');
  };

  useEffect(() => {
    if (!isCloudWorkflow) return undefined;
    const handleWorkspaceSwitching = () => {
      briefWebsiteRef.current.version += 1;
      briefWebsiteRef.current.origin = null;
      if (c5Enabled) {setForm({...createBriefFormDefaults(), websiteId:''}); setWebsiteError('');}
      briefKnowledgeRequestRef.current += 1;
      if (briefKnowledgeControllerRef.current) briefKnowledgeControllerRef.current.invalidate();
      setBriefKnowledge({ status: 'loading', brandVoices: [], icps: [], error: '' });
      setSelectedKnowledge(createBriefKnowledgeSelectionDefaults());
      setKnowledgeActionError('');
      if (!c5Enabled) setForm((current) => ({
        ...current,
        tone: DEFAULT_BRAND_VOICE_TONE,
        brandVoiceId: 'default',
        selectedBrandVoiceId: 'default',
        selectedBrandVoiceName: DEFAULT_BRAND_VOICE_LABEL,
        targetAudienceId: '',
        selectedIcpId: '',
        selectedIcpName: '',
        audience: ''
      }));
      resetStaleCloudWorkflow('Workspace changed before this article finished saving. Retry in the current Workspace.');
    };
    window.addEventListener('ranklyx:workspace-switching', handleWorkspaceSwitching);
    if (!c5Enabled) window.addEventListener('clicklyx:website-context-changed', handleWorkspaceSwitching);
    return () => {
      window.removeEventListener('ranklyx:workspace-switching', handleWorkspaceSwitching);
      if (!c5Enabled) window.removeEventListener('clicklyx:website-context-changed', handleWorkspaceSwitching);
    };
    // eslint-disable-next-line
  }, [isCloudWorkflow]);

  const mutateForm = (updater) => {
    if (!canMutateNow()) return false;
    briefAutosaveSuppressedRef.current = null;
    setForm(updater);
    return true;
  };
  const set = (k) => (v) => mutateForm((f) => ({ ...f, [k]: v }));
  const append = (k, v) => mutateForm((f) => ({ ...f, [k]: f[k] ? `${f[k]}, ${v}` : v }));
  const mutateOutline = (updater) => {
    if (!canMutateNow()) return false;
    outlineAutosaveSuppressedRef.current = null;
    setOutline(updater);
    return true;
  };

  useEffect(() => {
    if (canMutateBrief) return;
    briefAutosaveSuppressedRef.current = form;
    outlineAutosaveSuppressedRef.current = outline;
    cloudOutlineSaveRequestRef.current += 1;
    createInFlightRef.current = false;
    setCreating(false);
    setCreateStatus(null);
  }, [canMutateBrief, form, outline]);

  /* Prefill from a calendar card's "Start Brief" action. A fresh token signals a
     new hand-off, so we reset to a clean brief with just the card-derived fields
     filled (Topic, Primary keyword, Post type, Additional information) and jump
     back to step 1. Notes stay empty when the card had none. */
  useEffect(() => {
    if (!prefill || !prefill.token) return;
    setForm({
      ...createBriefFormDefaults(),
      ...(c5Enabled ? {websiteId:''} : {}),
      topic: prefill.topic || '',
      keyword: prefill.keyword || '',
      postType: prefill.postType || '',
      notes: prefill.notes || ''
    });
    setCloudIdentity(null);
    setCloudKnowledgeSnapshot(null);
    setSelectedKnowledge(createBriefKnowledgeSelectionDefaults());
    setKnowledgeActionError('');
    setCloudLoadState('idle');
    setCloudLoadError('');
    setOutline(null);
    setOutlineMeta(null);
    setOutlineSaveState('idle');
    setOutlineSaveError('');
    lastSavedCloudOutlineRef.current = null;
    setCloudResearch([]);
    setCloudDraft(null);
    setStep(1);
    // eslint-disable-next-line
  }, [prefill && prefill.token]);

  useEffect(() => {
    if (!briefRestoreRequest || !briefRestoreRequest.token || !briefRestoreRequest.form) return;
    if (c5Enabled && briefRestoreRequest.family !== websiteClient.briefFamily()) return;
    setForm((f) => ({ ...f, ...briefRestoreRequest.form }));
    setStep(1);
  }, [briefRestoreRequest && briefRestoreRequest.token]);

  const applyCloudLoadResult = (result) => {
    if (!result || result.ok !== true) {
      setCloudLoadState('error');
      setCloudLoadError(result && result.publicMessage || 'This article is unavailable in the current Workspace.');
      return;
    }
    setCloudIdentity(result.identity);
    setCloudKnowledgeSnapshot(result.article && result.article.meta && Object.prototype.hasOwnProperty.call(result.article.meta, 'knowledgeSnapshot')
      ? result.article.meta.knowledgeSnapshot
      : null);
    if (WF && typeof WF.writeCloudArticleRoute === 'function') WF.writeCloudArticleRoute(result.articleId);
    setForm({ ...createBriefFormDefaults(), ...(result.form || {}) });
    const loadedOutline = Array.isArray(result.outline) && result.outline.length ? result.outline : null;
    setOutline(loadedOutline);
    setOutlineMeta(null);
    lastSavedCloudOutlineRef.current = loadedOutline;
    setCloudResearch(Array.isArray(result.research) ? result.research : []);
    setCloudDraft(result.draft || null);
    setOutlineSaveState(loadedOutline ? 'saved' : 'idle');
    setOutlineSaveError('');
    const loadedStatus = String(result.article && result.article.status || '').trim().toLowerCase();
    if (loadedStatus === 'editing' && cloudDraftHasEditorHtml(result.draft) && replaceWithCloudEditor(result.articleId)) return;
    const restoredStep = Number(result.step);
    setStep((restoredStep === 1 || restoredStep === 2 || restoredStep === 3) ? restoredStep : (loadedOutline ? 2 : 1));
    setCloudLoadState('loaded');
    setCloudLoadError('');
  };

  const loadCloudArticleForOutline = (articleId) => {
    if (!WF || typeof WF.loadCloudArticle !== 'function') {
      setCloudLoadState('error');
      setCloudLoadError('Article storage is unavailable right now.');
      return Promise.resolve(null);
    }
    setCloudLoadState('loading');
    setCloudLoadError('');
    return WF.loadCloudArticle(articleId, {
      cloudClient: window.RankLyxCloudArticles,
      defaultForm: createBriefFormDefaults()
    }).then((result) => {
      applyCloudLoadResult(result);
      return result;
    });
  };

  /* ---- Foundation: hydrate the in-progress article on mount ----
     Legacy article hydration still uses ArticleStore. Cloud workflows load only by
     their explicit UUID route identity and never create a fallback art_ record. */
  const hydratedRef = useRef(false);
  useEffect(() => {
    if (hydratedRef.current) return;
    if (prefill && prefill.token) { hydratedRef.current = true; return; }
    hydratedRef.current = true;
    if (initialWorkflow.kind === 'cloud' && initialWorkflow.articleId) {
      loadCloudArticleForOutline(initialWorkflow.articleId);
      return;
    }
    if (!isLegacyWorkflow) return;
    try {
      const AS = window.ArticleStore;
      if (!AS) return;
      const rec = AS.loadActive(true);
      if (!rec) return;
      if (rec.brief && typeof rec.brief === 'object') {
        setForm((f) => ({
          ...f,
          ...rec.brief,
          brandVoiceId: rec.brief.brandVoiceId || 'default',
          selectedBrandVoiceId: rec.brief.selectedBrandVoiceId || rec.brief.brandVoiceId || 'default',
          selectedBrandVoiceName: rec.brief.selectedBrandVoiceName || (rec.brief.brandVoiceId === 'default' || !rec.brief.brandVoiceId ? DEFAULT_BRAND_VOICE_LABEL : ''),
          targetAudienceId: rec.brief.targetAudienceId || rec.brief.selectedIcpId || '',
          selectedIcpId: rec.brief.selectedIcpId || rec.brief.targetAudienceId || '',
          selectedIcpName: rec.brief.selectedIcpName || rec.brief.audience || ''
        }));
      }
      if (Array.isArray(rec.outline) && rec.outline.length) {
        setOutline(rec.outline);
        if (AS.stateIndex(rec.status) >= AS.stateIndex('outline')) setStep(2);
      }
    } catch (e) {}
    // eslint-disable-next-line
  }, []);

  /* ---- Foundation: persist the brief (debounced) ---- */
  useEffect(() => {
    if (!isLegacyWorkflow || !window.ArticleStore || !canMutateBrief || briefAutosaveSuppressedRef.current === form) return;
    const t = setTimeout(() => {
      if (!canMutateNow()) return;
      try { window.ArticleStore.setBrief(window.ArticleStore.getActiveArticleId(), form); } catch (e) {}
    }, 600);
    return () => clearTimeout(t);
  }, [form, isLegacyWorkflow, canMutateBrief]);

  /* ---- Foundation: persist the canonical outline whenever it changes ----
     setOutline guarantees stable section IDs (idempotent) and advances the
     article to the 'outline' state. We do NOT feed the return value back into
     React state - the in-state nodes already carry durable IDs. */
  useEffect(() => {
    if (!isLegacyWorkflow || !window.ArticleStore || !outline || !canMutateBrief || outlineAutosaveSuppressedRef.current === outline) return;
    if (!canMutateNow()) return;
    try { window.ArticleStore.setOutline(window.ArticleStore.getActiveArticleId(), outline); } catch (e) {}
  }, [outline, isLegacyWorkflow, canMutateBrief]);

  /* Create the cloud article first, then generate and save the outline to that same UUID. */
  const generateOutline = async () => {
    if (!canGenerateNow()) return false;
    if (creating || createInFlightRef.current) return;
    if (c5Enabled && !form.websiteId) {
      setWebsiteError(websiteClient.briefCopy.required);
      document.getElementById('c5-brief-website')?.focus();
      return false;
    }
    if (!WF || typeof WF.validateBriefForm !== 'function') {
      submit('Article storage is unavailable right now.', false, 'error');
      return;
    }
    const validation = WF.validateBriefForm(form);
    if (!validation.ok) {
      submit(validation.publicMessage, false, 'error');
      return;
    }
    let createKnowledgeSelection = null;
    if (!cloudIdentity) {
      if (briefKnowledge.status !== 'ready') {
        const message = briefKnowledge.status === 'error'
          ? 'Workspace Knowledge is unavailable right now. Try loading it again.'
          : 'Workspace Knowledge must finish loading before creating an outline.';
        setKnowledgeActionError(message);
        submit(message, false, 'error');
        return;
      }
      if (typeof WF.buildBriefKnowledgeSelection !== 'function') {
        setKnowledgeActionError('Workspace Knowledge is unavailable right now.');
        submit('Workspace Knowledge is unavailable right now.', false, 'error');
        return;
      }
      const resolvedSelection = WF.buildBriefKnowledgeSelection(form, selectedKnowledge, briefKnowledge);
      if (!resolvedSelection.ok) {
        setKnowledgeActionError(resolvedSelection.message);
        submit(resolvedSelection.message, false, 'error');
        return;
      }
      createKnowledgeSelection = resolvedSelection.knowledgeSelection;
      setKnowledgeActionError('');
    }
    const controller = getCloudController();
    if (!controller) {
      submit('Article storage is unavailable right now.', false, 'error');
      return;
    }
    createInFlightRef.current = true;
    setCreating(true);
    setCreateStatus('Creating article...');
    setCloudLoadError('');
    setOutlineSaveError('');
    try {
      const result = await controller.createOutline(form, {
        workflowIdentity: cloudIdentity,
        ...(c5Enabled ? {requireWebsite:true, origin:cloudIdentity && cloudIdentity.origin || briefWebsiteRef.current.origin} : {}),
        knowledgeSelection: createKnowledgeSelection,
        cloudClient: window.RankLyxCloudArticles,
        accessClient: window.ClicklyxWorkspaceAccess,
        runCreateOutline: window.runCreateOutline,
        adaptOutlineResultForUI: window.adaptOutlineResultForUI,
        onStatus: (status) => {if (canGenerateNow()) setCreateStatus(status);},
        onCloudIdentity: (identity, article) => {
          if (!canGenerateNow()) return;
          setCloudIdentity(identity);
          setCloudKnowledgeSnapshot(article && article.meta && Object.prototype.hasOwnProperty.call(article.meta, 'knowledgeSnapshot')
            ? article.meta.knowledgeSnapshot
            : null);
          if (WF && typeof WF.writeCloudArticleRoute === 'function') WF.writeCloudArticleRoute(identity.articleId);
        },
        onOutlineGenerated: (generated) => {
          setCloudIdentity(generated.identity);
          setOutline(generated.outline);
          setOutlineMeta(generated.meta);
          setOutlineSaveState('saving');
          setOutlineSaveError('');
          setStep(2);
        }
      });
      if (result && result.duplicate) return;
      if (result && result.stale) {
        resetStaleCloudWorkflow(result.publicMessage || 'Workspace changed before this article finished saving. Retry in the current Workspace.');
        return;
      }
      if (result && result.ok) {
        if(result.article) setCloudIdentity(WF.identityFromCloudArticle(result.article,window.RankLyxCloudArticles));
        lastSavedCloudOutlineRef.current = result.outline || outline;
        setOutlineSaveState('saved');
        setOutlineSaveError('');
        setStep(2);
        return;
      }
      if (result && result.stage === 'outline_save' && Array.isArray(result.outline)) {
        setOutlineSaveState('error');
        setOutlineSaveError(result.publicMessage || 'The outline was generated but could not be saved. Retry before continuing.');
        setStep(2);
        return;
      }
      const resultErrorCode = String(result && result.error && result.error.code || '');
      if (c5Enabled && result && result.stage === 'website') {
        setWebsiteError(result.publicMessage || websiteClient.briefCopy.unavailable);
        return false;
      }
      if (/^article_knowledge_/.test(resultErrorCode)) {
        setKnowledgeActionError(result.publicMessage || 'Workspace Knowledge changed. Reload latest and choose again.');
      }
      submit(result && result.publicMessage || 'The outline could not be generated. Please try again.', false, 'error');
    } catch (e) {
      if (!canGenerateNow()) return false;
      console.error('[Create Outline] failed:', e);
      submit('The outline could not be generated. Please try again. If this keeps happening, contact support.', false, 'error');
    } finally {
      createInFlightRef.current = false;
      setCreating(false);
      setCreateStatus(null);
    }
  };

  const retryCloudOutlineSave = () => {
    if (!cloudIdentity || !outline || !WF || creating || cloudOutlineSaveInFlightRef.current) return;
    const controller = getCloudController();
    if (!controller) return;
    const canComplete = controller.hasPendingCompletion(cloudIdentity.articleId, outline);
    if (!canMutateNow() && !canComplete) return false;
    const requestId = cloudOutlineSaveRequestRef.current + 1;
    cloudOutlineSaveRequestRef.current = requestId;
    cloudOutlineSaveInFlightRef.current = true;
    setOutlineSaveState('saving');
    setOutlineSaveError('');
    Promise.resolve().then(() => controller.retryOutlineSave(cloudIdentity.articleId, outline, form, {
      expectedRevision: cloudIdentity.revision,
      cloudClient: window.RankLyxCloudArticles,
      accessClient: window.ClicklyxWorkspaceAccess
    })).then((result) => {
      cloudOutlineSaveInFlightRef.current = false;
      if ((!canMutateNow() && !canComplete) || cloudOutlineSaveRequestRef.current !== requestId) return;
      if (result && result.stale) {
        resetStaleCloudWorkflow(result.publicMessage || 'Workspace changed before this article finished saving. Retry in the current Workspace.');
        return;
      }
      if (result && result.ok) {
        const saved = result.article;
        if (!saved || saved.id !== cloudIdentity.articleId || !Array.isArray(saved.outline) ||
          !/^[1-9][0-9]*$/.test(String(saved.revision)) || !Number.isSafeInteger(Number(saved.revision)) ||
          (!canComplete && Number(saved.revision) !== Number(cloudIdentity.revision) + 1)) {
          throw new Error('outline_save_acknowledgement_invalid');
        }
        setCloudIdentity(WF.identityFromCloudArticle(saved, window.RankLyxCloudArticles));
        lastSavedCloudOutlineRef.current = outline;
        setOutlineSaveState('saved');
        setOutlineSaveError('');
        return;
      }
      setOutlineSaveState('error');
      setOutlineSaveError(result && result.publicMessage || 'The outline could not be saved. Retry before continuing.');
    }).catch(() => {
      cloudOutlineSaveInFlightRef.current = false;
      if ((!canMutateNow() && !canComplete) || cloudOutlineSaveRequestRef.current !== requestId) return;
      setOutlineSaveState('error');
      setOutlineSaveError('The outline save could not be confirmed. Keep your changes and retry before continuing.');
    });
  };

  useEffect(() => {
    if (!cloudIdentity || step !== 2 || !outline || !canMutateBrief || outlineAutosaveSuppressedRef.current === outline) return undefined;
    // Debouncing is cancelable; an active PATCH is not. A newer outline waits
    // for its acknowledgement and uses the returned revision before saving.
    if (lastSavedCloudOutlineRef.current === outline || creating || cloudOutlineSaveInFlightRef.current || outlineSaveState === 'error') return undefined;
    setOutlineSaveState('saving');
    setOutlineSaveError('');
    const timer = window.setTimeout(() => {
      if (!canMutateNow()) return;
      retryCloudOutlineSave();
    }, 700);
    return () => window.clearTimeout(timer);
    // eslint-disable-next-line
  }, [outline, cloudIdentity && cloudIdentity.articleId, cloudIdentity && cloudIdentity.revision, step, canMutateBrief, creating, outlineSaveState]);
  /* Explicit Outline -> Brief reset. The visual stepper is not navigation. */
  const clearOutlineResearchNotes = (outlineNodes) => {
    const RA = window.ResearchAgent;
    const AS = window.ArticleStore;
    if (!RA || typeof RA.softDeleteArticleResearchNote !== 'function' || !AS) return;
    const articleId = AS.getActiveArticleId && AS.getActiveArticleId();
    (outlineNodes || []).forEach((s) => {
      if (!s) return;
      const ids = [s.id].concat((s.children || []).map((c) => c && c.id)).filter(Boolean);
      ids.forEach((headingId) => {
        try {
          RA.softDeleteArticleResearchNote({
            userId: RA.AUTH && RA.AUTH.userId,
            workspaceId: RA.AUTH && RA.AUTH.workspaceId,
            articleId,
            headingId
          });
        } catch (e) {}
      });
    });
  };

  const backToBriefFromOutline = () => {
    if (!canMutateNow()) {
      setStep(1);
      return true;
    }
    if (isLegacyWorkflow) clearOutlineResearchNotes(outline);
    setOutline(null);
    setOutlineMeta(null);
    setOutlineSaveState('idle');
    setOutlineSaveError('');
    lastSavedCloudOutlineRef.current = null;
    setCreateStatus(null);
    setCreating(false);
    setStep(1);
    if (!isLegacyWorkflow) return;
    try {
      const AS = window.ArticleStore;
      if (AS) {
        const articleId = AS.getActiveArticleId && AS.getActiveArticleId();
        if (AS.patch) AS.patch(articleId, { outline: [], status: 'brief' });
        else if (AS.setStatus) AS.setStatus(articleId, 'brief');
      }
    } catch (e) {}
  };

  /* completion ratio for header progress bar */
  const filled = ['topic', 'keyword', 'postType', 'brandVoiceId'].filter(
    (k) => form[k].trim().length > 0
  ).length;
  const pct = Math.round(filled / 4 * 100);

  const submit = (label, primary, kind) => {
    setToast({ label, primary, kind: kind || (primary ? 'primary' : 'success') });
    setTimeout(() => setToast(null), 2200);
  };

  const applyCloudBrandVoice = (voice) => {
    if (!canMutateNow()) return false;
    if (!voice || !voice.id || !voice.updatedAt) return false;
    mutateForm((current) => ({
      ...current,
      brandVoiceId: voice.id,
      selectedBrandVoiceId: voice.id,
      selectedBrandVoiceName: voice.name,
      tone: current.tone || DEFAULT_BRAND_VOICE_TONE
    }));
    setSelectedKnowledge((current) => ({
      ...current,
      brandVoice: {
        kind: 'custom',
        id: voice.id,
        expectedUpdatedAt: voice.updatedAt
      }
    }));
    setKnowledgeActionError('');
    return true;
  };

  const applyCloudIcp = (icp) => {
    if (!canMutateNow()) return false;
    if (!icp || !icp.id || !icp.updatedAt) return false;
    mutateForm((current) => ({
      ...current,
      targetAudienceId: icp.id,
      selectedIcpId: icp.id,
      selectedIcpName: icp.name,
      audience: icp.name
    }));
    setSelectedKnowledge((current) => ({
      ...current,
      icp: {
        id: icp.id,
        expectedUpdatedAt: icp.updatedAt
      }
    }));
    setKnowledgeActionError('');
    return true;
  };

  const chooseWebsite = (id) => {
    if (!canMutateNow() || creating || cloudIdentity || id === formRef.current.websiteId) return;
    const site = websites.websites.find(item => item.id === id);
    if (id && (!site || !site.canWrite)) {setWebsiteError(site ? websiteClient.briefCopy.readonlyExplanation : websiteClient.briefCopy.unavailable); return;}
    briefWebsiteRef.current.version += 1; briefWebsiteRef.current.origin = null;
    briefKnowledgeRequestRef.current += 1;
    if (briefKnowledgeControllerRef.current) briefKnowledgeControllerRef.current.invalidate();
    setBriefKnowledge({status:'ready',brandVoices:[],icps:[],error:''});
    setSelectedKnowledge(createBriefKnowledgeSelectionDefaults());
    setKnowledgeActionError(''); setWebsiteError('');
    mutateForm(current => ({...current,websiteId:id,brandVoiceId:'default',selectedBrandVoiceId:'default',
      selectedBrandVoiceName:DEFAULT_BRAND_VOICE_LABEL,tone:DEFAULT_BRAND_VOICE_TONE,
      targetAudienceId:'',selectedIcpId:'',selectedIcpName:'',audience:''}));
  };
  useEffect(() => {
    if (!c5Enabled || cloudIdentity || !form.websiteId || websites.status !== 'ready') return;
    const site = websites.websites.find(item => item.id === form.websiteId);
    if (!site || !site.canWrite) {chooseWebsite(''); setWebsiteError(websiteClient.briefCopy.unavailable);}
  }, [websites, form.websiteId, cloudIdentity]);

  const loadBriefKnowledge = (selectionRequest) => {
    const controller = getBriefKnowledgeController();
    const requestId = briefKnowledgeRequestRef.current + 1;
    briefKnowledgeRequestRef.current = requestId;
    if (c5Enabled && !formRef.current.websiteId) {
      setBriefKnowledge({status:'ready',brandVoices:[],icps:[],error:''});
      return Promise.resolve(null);
    }
    setBriefKnowledge((current) => ({ ...current, ...(c5Enabled ? {brandVoices:[],icps:[]} : {}), status: 'loading', error: '' }));
    setKnowledgeActionError('');
    if (!controller) {
      setBriefKnowledge((current) => ({
        ...current,
        status: 'error',
        error: 'Workspace Knowledge is unavailable right now.'
      }));
      return Promise.resolve(null);
    }
    const siteId = formRef.current.websiteId;
    const family = c5Enabled ? websiteClient.briefFamily() : null;
    const version = ++briefWebsiteRef.current.version;
    return Promise.resolve().then(async () => {
      if (c5Enabled) {
        briefWebsiteRef.current.origin = null;
        const context = await window.ClicklyxWebsiteContext.getContext(siteId);
        if (briefKnowledgeRequestRef.current !== requestId || formRef.current.websiteId !== siteId || family !== websiteClient.briefFamily()) return {ok:false,stale:true};
        if (context.context.mode !== 'strict') throw new Error('Inactive Website contract');
        briefWebsiteRef.current.origin = window.ClicklyxWebsiteContext.capturePage(siteId, () => version === briefWebsiteRef.current.version && formRef.current.websiteId === siteId);
      }
      return controller.load();
    }).then((result) => {
      if (briefKnowledgeRequestRef.current !== requestId || result && result.stale) return result;
      if (!result || result.ok !== true) {
        setBriefKnowledge((current) => ({
          ...current,
          status: 'error',
          error: result && result.publicMessage || 'Workspace Knowledge is unavailable right now.'
        }));
        return result;
      }
      const nextKnowledge = {
        status: 'ready',
        brandVoices: result.brandVoices || [],
        icps: result.icps || [],
        origin: result.origin,
        error: ''
      };
      setBriefKnowledge(nextKnowledge);
      if (!c5Enabled && selectionRequest && WF && typeof WF.resolveBriefKnowledgeReturnSelection === 'function') {
        const returned = WF.resolveBriefKnowledgeReturnSelection(selectionRequest, nextKnowledge);
        if (!returned) {
          setKnowledgeActionError(selectionRequest.type === 'icp'
            ? 'The requested ICP is no longer available. Choose another.'
            : 'The requested Brand Voice is no longer available. Choose another.');
          return result;
        }
        if (selectionRequest.type === 'icp') applyCloudIcp(returned);
        else applyCloudBrandVoice(returned);
        return result;
      }
      if (WF && typeof WF.buildBriefKnowledgeSelection === 'function') {
        const verification = WF.buildBriefKnowledgeSelection(formRef.current, selectedKnowledge, nextKnowledge);
        if (!verification.ok) setKnowledgeActionError(verification.message);
      }
      return result;
    }).catch(() => {
      if (briefKnowledgeRequestRef.current !== requestId) return {ok:false,stale:true};
      setBriefKnowledge({status:'error',brandVoices:[],icps:[],error:c5Enabled ? websiteClient.briefCopy.unavailable : 'Workspace Knowledge is unavailable right now.'});
      return {ok:false};
    });
  };

  const selectedVoiceId = String(form.selectedBrandVoiceId || form.brandVoiceId || 'default');
  const currentVoiceAvailable = selectedVoiceId === 'default' ||
    briefKnowledge.brandVoices.some((voice) => voice.id === selectedVoiceId);
  const unavailableVoiceOption = selectedVoiceId !== 'default' && !currentVoiceAvailable
    ? [{
      value: selectedVoiceId,
      label: (form.selectedBrandVoiceName || 'Selected Brand Voice') + ' (unavailable)',
      unavailable: true
    }]
    : [];
  const brandVoiceOptions = [
    { value: 'default', label: DEFAULT_BRAND_VOICE_LABEL }
  ].concat(briefKnowledge.brandVoices.map((voice) => ({
    value: voice.id,
    label: voice.name,
    updatedAt: voice.updatedAt
  }))).concat(unavailableVoiceOption).concat([
    { value: 'create-custom', label: 'Create custom voice' }
  ]);

  const selectedIcpId = String(form.selectedIcpId || form.targetAudienceId || '');
  const currentIcpAvailable = !selectedIcpId ||
    briefKnowledge.icps.some((icp) => icp.id === selectedIcpId);
  const unavailableIcpOption = selectedIcpId && !currentIcpAvailable
    ? [{
      value: selectedIcpId,
      label: (form.selectedIcpName || form.audience || 'Selected ICP') + ' (unavailable)',
      unavailable: true
    }]
    : [];
  const targetAudienceOptions = (c5Enabled ? [{value:'',label:'No ICP selected yet'}] : []).concat(briefKnowledge.icps.map((icp) => ({
    value: icp.id,
    label: icp.name,
    updatedAt: icp.updatedAt
  }))).concat(unavailableIcpOption).concat(
    briefKnowledge.icps.length < 3 ? [{ value: 'create-icp', label: 'Create ideal customer profile' }] : []
  );

  const selectBrandVoice = (value, option) => {
    if (!canMutateNow()) return false;
    if (value === 'create-custom') {
      if (c5Enabled && !form.websiteId) {setWebsiteError(websiteClient.briefCopy.required); document.getElementById('c5-brief-website')?.focus(); return;}
      if (onCreateKnowledge) onCreateKnowledge('brand-voice', form);
      else submit('Open Brand Voice from Knowledge to create a custom voice.', false);
      return;
    }
    if (option && option.unavailable) {
      setKnowledgeActionError('The selected Brand Voice is no longer available. Choose another.');
      return;
    }
    if (value === 'default') {
      mutateForm((current) => ({
        ...current,
        brandVoiceId: 'default',
        selectedBrandVoiceId: 'default',
        selectedBrandVoiceName: DEFAULT_BRAND_VOICE_LABEL,
        tone: DEFAULT_BRAND_VOICE_TONE
      }));
      setSelectedKnowledge((current) => ({ ...current, brandVoice: { kind: 'default' } }));
      setKnowledgeActionError('');
      return;
    }
    applyCloudBrandVoice({
      id: value,
      name: option && option.label || '',
      updatedAt: option && option.updatedAt || ''
    });
  };

  const selectTargetAudience = (value, option) => {
    if (!canMutateNow()) return false;
    if (value === 'create-icp') {
      if (c5Enabled && !form.websiteId) {setWebsiteError(websiteClient.briefCopy.required); document.getElementById('c5-brief-website')?.focus(); return;}
      if (onCreateKnowledge) onCreateKnowledge('audience-icp', form);
      else submit('Open ICP Knowledge to create an ideal customer profile.', false);
      return;
    }
    if (c5Enabled && !value) {
      mutateForm(current => ({...current,targetAudienceId:'',selectedIcpId:'',selectedIcpName:'',audience:''}));
      setSelectedKnowledge(current => ({...current,icp:null})); setKnowledgeActionError(''); return;
    }
    if (option && option.unavailable) {
      setKnowledgeActionError('The selected ICP is no longer available. Choose another.');
      return;
    }
    applyCloudIcp({
      id: value,
      name: option && option.label || '',
      updatedAt: option && option.updatedAt || ''
    });
  };

  useEffect(() => {
    loadBriefKnowledge();
    return () => {
      briefKnowledgeRequestRef.current += 1;
      if (briefKnowledgeControllerRef.current) briefKnowledgeControllerRef.current.invalidate();
    };
    // eslint-disable-next-line
  }, [c5Enabled ? form.websiteId : null]);

  useEffect(() => () => {briefWebsiteRef.current.version += 1; if (briefKnowledgeControllerRef.current) briefKnowledgeControllerRef.current.dispose();}, []);

  useEffect(() => {
    if (!knowledgeSelectionRequest || !knowledgeSelectionRequest.token) return;
    if (c5Enabled && knowledgeSelectionRequest.family !== websiteClient.briefFamily()) return;
    loadBriefKnowledge(c5Enabled ? null : knowledgeSelectionRequest);
    // eslint-disable-next-line
  }, [knowledgeSelectionRequest && knowledgeSelectionRequest.token]);
  const handleCloudResearchSaved = (research, article) => {
    setCloudResearch(Array.isArray(research) ? research : []);
    if (article) setCloudIdentity(WF.identityFromCloudArticle(article, window.RankLyxCloudArticles));
  };

  const handleCloudDraftSaved = (draft, article) => {
    setCloudDraft(draft || null);
    if (article) setCloudIdentity(WF.identityFromCloudArticle(article, window.RankLyxCloudArticles));
  };
  useLucide([toast, pct, cloudLoadState, outlineSaveState]);

  const textareaRef = useRef(null);
  const summaryCardRef = useRef(null);
  const formCardRef = useRef(null);

  if (isCloudWorkflow && cloudLoadState === 'loading') {
    return (
      <div className="rl-page" data-screen-label="Create Content Brief">
        <div className="rl-page__inner">
          <div className="rl-brief-header">
            <h1>Create an article</h1>
            <p className="rl-brief-header__lede">Loading the saved brief and outline for this Workspace</p>
          </div>
          <div className="rl-card">
            <div className="rl-card__body" role="status" aria-live="polite" style={{ display: 'flex', alignItems: 'center', gap: '10px', minHeight: '120px' }}>
              <span className="rl-osum__spinner rl-osum__spinner--dark"></span>
              <span>Loading article...</span>
            </div>
          </div>
        </div>
      </div>);
  }

  if (isCloudWorkflow && cloudLoadState === 'error') {
    return (
      <div className="rl-page" data-screen-label="Create Content Brief">
        <div className="rl-page__inner">
          <div className="rl-brief-header">
            <h1>Create an article</h1>
            <p className="rl-brief-header__lede">This article could not be opened in the current Workspace</p>
          </div>
          <div className="rl-card">
            <div className="rl-card__body" role="alert" style={{ display: 'grid', gap: '14px', minHeight: '120px', alignContent: 'center' }}>
              <p style={{ margin: 0, color: 'var(--rl-danger)', lineHeight: '22px' }}>{cloudLoadError || 'This article is unavailable in the current Workspace.'}</p>
              {initialWorkflow.articleId &&
              <button type="button" className="rl-btn rl-btn--secondary" style={{ width: 'fit-content' }} onClick={() => loadCloudArticleForOutline(initialWorkflow.articleId)}>
                <span>Retry</span>
              </button>}
            </div>
          </div>
        </div>
      </div>);
  }

  const blockUnstartedCloudWorkflow = isCloudWorkflow && !cloudIdentity && !canGenerateBrief && !hadFullAccessRef.current;
  if (blockUnstartedCloudWorkflow) {
    const checkingAccess = !workspaceAccess || workspaceAccess.status === 'loading';
    return (
      <div className="rl-page" data-screen-label="Create Content Brief">
        <div className="rl-page__inner">
          <div className="rl-brief-header">
            <h1>Create an article</h1>
            <p className="rl-brief-header__lede">{checkingAccess ? 'Checking Workspace access before starting a new Article' : 'Article creation is unavailable in this Workspace'}</p>
          </div>
          <div className="rl-card">
            <div className="rl-card__body" role="status" style={{ display: 'grid', gap: '14px', minHeight: '120px', alignContent: 'center' }}>
              <p style={{ margin: 0, color: 'var(--rl-fg-2)', lineHeight: '22px' }}>
                {checkingAccess ? 'Existing content remains available while access is checked.' : 'Open Articles to view content already saved in this Workspace.'}
              </p>
              <button type="button" className="rl-btn rl-btn--secondary" style={{ width: 'fit-content' }} onClick={() => onSafeNavigate && onSafeNavigate('articles')}>
                <i data-lucide="arrow-left"></i><span>Back to Articles</span>
              </button>
            </div>
          </div>
        </div>
      </div>);
  }

  return (
    <div className="rl-page" data-screen-label="Create Content Brief">
      <div className="rl-page__inner">
        <div className="rl-brief-header">
          <h1>Create an article</h1>
          <p className="rl-brief-header__lede">Build the brief that will guide your outline, research, and draft</p>
        </div>
        <Stepper step={step} />

        {step === 1 &&
        <div className="rl-brief-step">
          <div className="rl-brief-layout">
            <div className="rl-brief-main">
              <div className="rl-card" ref={formCardRef}>
                <form
                    className="rl-card__body"
                    noValidate={c5Enabled}
                    onSubmit={(e) => {e.preventDefault();generateOutline();}}>

                  <Field label="Topic">
                    <TextInput
                        value={form.topic}
                        onChange={set('topic')}
                        readOnly={!canMutateBrief}
                        placeholder="Example: How to improve SaaS onboarding" />

                  </Field>

                  <Field label="Primary keyword">
                    <TextInput
                        value={form.keyword}
                        onChange={set('keyword')}
                        readOnly={!canMutateBrief}
                        placeholder="Example: SaaS onboarding best practices" />

                  </Field>

                  <Field label="Post type">
                    <SelectInput
                        value={form.postType}
                        onChange={set('postType')}
                        disabled={!canMutateBrief}
                        placeholder="Select a post type"
                        options={['Guide', 'Product Roundup', 'Product Comparison', 'Single Product Review']} />
                  </Field>

                  {c5Enabled && <window.ClicklyxWebsitesUI.BriefWebsiteField value={form.websiteId} state={websites} error={websiteError}
                    SelectComponent={SelectInput}
                    disabled={!canMutateBrief || creating || !!cloudIdentity} onChange={chooseWebsite} onAdd={() => onSafeNavigate && onSafeNavigate('websites')} />}

                  <Field label="Brand voice">
                    <SelectInput
                        value={form.brandVoiceId}
                        onChange={selectBrandVoice}
                        disabled={!canMutateBrief}
                        placeholder="Select a brand voice"
                        options={brandVoiceOptions} />
                  </Field>

                  <Field label="Target audience" optional full={!c5Enabled}>
                    <SelectInput
                        value={form.targetAudienceId}
                        onChange={selectTargetAudience}
                        disabled={!canMutateBrief}
                        placeholder="No ICP selected yet"
                        options={targetAudienceOptions} />
                  </Field>

                  <Field
                      label="Additional information"
                      optional
                      full>

                    <div className="rl-textarea-wrap">
                      <textarea
                          ref={textareaRef}
                          className="rl-textarea"
                          value={form.notes}
                          readOnly={!canMutateBrief}
                          aria-readonly={!canMutateBrief ? 'true' : undefined}
                          onChange={(e) => {if (canMutateNow()) set('notes')(e.target.value);}}
                          placeholder="Add notes, examples, internal links, product details, or anything the AI should consider."
                          maxLength={2000} />

                      <span className="count">{form.notes.length} / 2000</span>
                    </div>
                  </Field>
                </form>
              </div>
            </div>

            <div className="rl-brief-rail">
              <BriefSummary form={form} cardRef={summaryCardRef} />
            </div>
          </div>

          <div className="rl-brief-actions">
            {!cloudIdentity && briefKnowledge.status === 'loading' &&
            <div className="rl-research-progress" role="status" aria-live="polite">
              <span className="rl-osum__spinner rl-osum__spinner--dark"></span>
              <div className="rl-research-progress__txt">
                <span className="rl-research-progress__step">Loading Workspace Knowledge...</span>
              </div>
            </div>}
            {!cloudIdentity && briefKnowledge.status === 'error' &&
            <React.Fragment>
              <div className="rl-research-progress" role="alert">
                <div className="rl-research-progress__txt">
                  <span className="rl-research-progress__step">{briefKnowledge.error || 'Workspace Knowledge is unavailable right now.'}</span>
                </div>
              </div>
              <button type="button" className="rl-btn rl-btn--secondary" onClick={() => loadBriefKnowledge()}>
                Try again
              </button>
            </React.Fragment>}
            {!cloudIdentity && briefKnowledge.status === 'ready' && knowledgeActionError &&
            <React.Fragment>
              <div className="rl-research-progress" role="alert">
                <div className="rl-research-progress__txt">
                  <span className="rl-research-progress__step">{knowledgeActionError}</span>
                </div>
              </div>
              <button type="button" className="rl-btn rl-btn--secondary" onClick={() => loadBriefKnowledge()}>
                Reload latest
              </button>
            </React.Fragment>}
            <button
              type="button"
              className="rl-btn rl-btn--primary"
              onClick={generateOutline}
              disabled={!canGenerateBrief || creating || (!c5Enabled && !cloudIdentity && briefKnowledge.status !== 'ready')}
              aria-describedby={!canGenerateBrief ? accessDescriptionId : undefined}>
              {creating ?
              <React.Fragment><span className="rl-osum__spinner"></span><span>Creating...</span></React.Fragment> :
              <span>Create outline</span>}
            </button>
            {outline && !canGenerateBrief &&
            <button type="button" className="rl-btn rl-btn--secondary" onClick={() => setStep(2)}>
              <span>View saved outline</span><i data-lucide="arrow-right"></i>
            </button>}
            {creating && createStatus &&
            <div className="rl-research-progress" role="status" aria-live="polite">
              <span className="rl-osum__spinner rl-osum__spinner--dark"></span>
              <div className="rl-research-progress__txt">
                <span className="rl-research-progress__step">{createStatus}</span>
              </div>
            </div>}
          </div>
        </div>
        }

        {step === 2 && outline &&
          <OutlineScreen
            outline={outline}
          setOutline={mutateOutline}
          form={form}
          meta={outlineMeta}
          workflowIdentity={isLegacyWorkflow ? { kind: 'legacy' } : cloudIdentity}
          workflowKnowledgeSnapshot={isLegacyWorkflow ? null : cloudKnowledgeSnapshot}
          workflowResearch={cloudResearch}
          outlineSaveState={outlineSaveState === 'saved' && lastSavedCloudOutlineRef.current !== outline ? 'saving' : outlineSaveState}
          outlineSaveError={outlineSaveError}
          canCompleteOutline={!!(cloudIdentity && getCloudController() && getCloudController().hasPendingCompletion(cloudIdentity.articleId, outline))}
          onRetryOutlineSave={retryCloudOutlineSave}
          onCloudResearchSaved={handleCloudResearchSaved}
          workspaceAccess={workspaceAccess}
          onBack={backToBriefFromOutline}
          onGenerateDraft={() => { if (!canGenerateNow()) return false; try { console.log('write-button-clicked'); } catch (e) {} submit('Writing article...', true); setStep(3); return true; }} />
        }

        {step === 3 &&
        <DraftGenerating form={form} outline={outline} workflowIdentity={isLegacyWorkflow ? { kind: 'legacy' } : cloudIdentity} cloudResearch={cloudResearch} cloudDraft={cloudDraft} workspaceAccess={workspaceAccess} onCloudDraftSaved={handleCloudDraftSaved} onBack={() => setStep(2)} />
        }

        {step === 4 &&
        <StepPlaceholder step={step} onBack={() => setStep(2)} />
        }
      </div>

      {toast &&
      <div className={'rl-toast' + (toast.kind === 'error' ? ' rl-toast--error' : '')} role={toast.kind === 'error' ? 'alert' : 'status'}>
          <i data-lucide={toast.kind === 'error' ? 'alert-circle' : toast.primary ? 'sparkles' : 'check'}></i>
          <span>{toast.label}</span>
        </div>
      }
    </div>);

}

/* ------------------------------------------------------------------ */
/* Draft generation â†’ runs the AI Writing Agent, then opens the Article
   Editor. The Writing Agent BRAIN (window.WritingAgent) does the work;
   this screen only orchestrates the call, surfaces calm progress, and
   handles success / failure. It NEVER clears the brief, outline, or
   research notes - a failed run leaves everything intact to retry. */
function DraftGenerating({ form, outline, workflowIdentity, cloudResearch, cloudDraft, workspaceAccess, onCloudDraftSaved, onBack }) {
  const isCloudWorkflow = !!(workflowIdentity && workflowIdentity.kind === 'cloud');
  const hasRestoredCloudDraft = !!(isCloudWorkflow && cloudDraft && typeof cloudDraft === 'object' && (
    (typeof cloudDraft.html === 'string' && cloudDraft.html.trim()) ||
    (typeof cloudDraft.markdown === 'string' && cloudDraft.markdown.trim()) ||
    (typeof cloudDraft.text === 'string' && cloudDraft.text.trim()) ||
    (typeof cloudDraft.content === 'string' && cloudDraft.content.trim()) ||
    (Array.isArray(cloudDraft.sections) && cloudDraft.sections.length)
  ));
  const [phase, setPhase] = useState(hasRestoredCloudDraft ? 'Draft saved' : 'Preparing article context');
  const [status, setStatus] = useState(hasRestoredCloudDraft ? 'success' : 'writing'); // 'writing' | 'saving' | 'success' | 'error' | 'save-error'
  const [errMsg, setErrMsg] = useState('');
  const ranRef = useRef(false);
  const redirectRef = useRef(null);
  const mountedRef = useRef(false);
  const cloudDraftControllerRef = useRef(null);
  const cloudUnsavedDraftRef = useRef(null);
  const cloudSaveRequestRef = useRef(0);
  const cloudNavigationInvalidatedRef = useRef(false);
  const accessRef = useRef(workspaceAccess);
  accessRef.current = workspaceAccess;
  const canMutateDraft = !!(workspaceAccess && workspaceAccess.canMutateWorkspaceContent === true);
  const canGenerateDraft = !!(canMutateDraft && workspaceAccess && workspaceAccess.canUseAi === true);
  const canMutateNow = () => !!(accessRef.current && accessRef.current.canMutateWorkspaceContent === true);
  const canGenerateNow = () => !!(canMutateNow() && accessRef.current && accessRef.current.canUseAi === true);

  const getCloudDraftController = () => {
    const WF = window.RankLyxArticleWorkflow;
    if (!cloudDraftControllerRef.current && WF && typeof WF.createCloudDraftController === 'function') {
      cloudDraftControllerRef.current = WF.createCloudDraftController();
    }
    return cloudDraftControllerRef.current;
  };

  /* Map the Writing Agent's progress events to calm, user-facing messages.
     For body sections we surface the actual section being written. */
  const onProgress = (event, data) => {
    if (!canGenerateNow()) return;
    data = data || {};
    if (event === 'writing-context-ready') setPhase('Preparing article context');
    else if (event === 'writing-section-start') {
      if (data.kind === 'intro') setPhase('Writing introduction');
      else if (data.kind === 'conclusion') setPhase('Writing conclusion');
      else setPhase(data.title ? ('Writing section: ' + data.title) : 'Writing article sections');
    }
    else if (event === 'writing-validation-complete') setPhase('Checking draft quality');
    else if (event === 'writing-repair-start') setPhase('Writer is refining a few sections');
    else if (event === 'writing-saving-draft') setPhase('Saving draft');
    else if (event === 'writing-complete') setPhase('Draft ready');
  };

  const scheduleCloudEditorOpen = () => {
    if (!isCloudWorkflow || redirectRef.current || cloudNavigationInvalidatedRef.current) return;
    const articleId = workflowIdentity && workflowIdentity.articleId;
    const WF = window.RankLyxArticleWorkflow;
    const cloudClient = window.RankLyxCloudArticles;
    const epoch = cloudClient && typeof cloudClient.getRequestEpoch === 'function' ? cloudClient.getRequestEpoch() : 0;
    let href = '';
    try {
      href = WF && typeof WF.buildCloudEditorUrl === 'function'
        ? WF.buildCloudEditorUrl(articleId, cloudClient)
        : '';
    } catch (e) { href = ''; }
    if (!href) return;
    redirectRef.current = setTimeout(() => {
      redirectRef.current = null;
      if (!mountedRef.current || cloudNavigationInvalidatedRef.current) return;
      if (cloudClient && typeof cloudClient.isStaleRequestEpoch === 'function' && cloudClient.isStaleRequestEpoch(epoch)) return;
      try { console.log('cloud-write-open-editor', { articleId, via: 'auto' }); } catch (e) {}
      if (window.location && typeof window.location.replace === 'function') window.location.replace(href);
      else window.location.href = href;
    }, 3000);
  };

  const handleCloudDraftResult = (result) => {
    if (!mountedRef.current) return;
    if (!canGenerateNow() && !hasRestoredCloudDraft) {
      setPhase('Read-only mode');
      setErrMsg('Draft generation is unavailable while this Workspace is read-only.');
      setStatus('blocked');
      return;
    }
    if (result && result.stale) {
      cloudUnsavedDraftRef.current = null;
      setErrMsg(result.publicMessage || 'Workspace changed before this draft finished saving. Retry in the current Workspace.');
      setStatus('error');
      return;
    }
    if (result && result.ok) {
      const draftResult = result.draftResult || (cloudUnsavedDraftRef.current && cloudUnsavedDraftRef.current.draftResult) || cloudDraft || null;
      cloudUnsavedDraftRef.current = null;
      setPhase('Draft saved');
      setStatus('success');
      if (onCloudDraftSaved) onCloudDraftSaved(draftResult, result.article);
      scheduleCloudEditorOpen();
      return;
    }
    if (result && result.stage === 'draft_save' && result.draftResult) {
      cloudUnsavedDraftRef.current = { draftResult: result.draftResult, form: result.form || form };
      setPhase('Draft written');
      setErrMsg(result.publicMessage || 'The draft was generated but could not be saved. Retry before continuing.');
      setStatus('save-error');
      return;
    }
    setErrMsg(result && result.publicMessage || getDraftPublicErrorMessage(result && result.draftResult ? result.draftResult : result));
    setStatus('error');
  };

  const runCloudGeneration = async () => {
    if (!canGenerateNow()) return;
    const articleId = workflowIdentity && workflowIdentity.articleId;
    const controller = getCloudDraftController();
    await waitForWritingRuntime();
    if (!canGenerateNow()) return;
    const WA = window.WritingAgent;
    const appLLMAdapter = (typeof window !== 'undefined' && typeof window.appLLMAdapter === 'function')
      ? window.appLLMAdapter
      : null;
    logWritingRuntime('cloud-write-article-click', { articleId });
    if (!articleId || !controller) { setStatus('error'); setErrMsg('Article storage is unavailable right now.'); return; }
    if (!WA || typeof WA.generateArticleDraft !== 'function') { setStatus('error'); setErrMsg('Writing engine script failed to load'); return; }

    try { console.log('cloud-write-generation-start', { articleId }); } catch (e) {}
    controller.generateDraft(articleId, {
      cloudClient: window.RankLyxCloudArticles,
      accessClient: window.ClicklyxWorkspaceAccess,
      defaultForm: form,
      writingAgent: WA,
      llmAdapter: appLLMAdapter,
      onProgress,
      onDraftGenerated: (generated) => {
        if (!canGenerateNow()) return;
        cloudUnsavedDraftRef.current = generated || null;
        setPhase('Saving draft');
      }
    }).then((result) => {
      if (!canGenerateNow()) {
        handleCloudDraftResult(result);
        return;
      }
      if (result && result.ok) {
        try { console.log('cloud-write-generation-success', { articleId, words: (result.draftResult && result.draftResult.html || '').length, source: result.draftResult && result.draftResult.source }); } catch (e) {}
      }
      handleCloudDraftResult(result);
    }).catch((e) => {
      if (!mountedRef.current || !canGenerateNow()) return;
      try { console.log('cloud-write-generation-error', { error: e && e.message }); } catch (_) {}
      setErrMsg(DRAFT_GENERIC_PUBLIC_ERROR);
      setStatus('error');
    });
  };

  const runLegacyGeneration = async () => {
    if (!canGenerateNow()) return;
    await waitForWritingRuntime();
    if (!canGenerateNow()) return;
    const AS = window.ArticleStore;
    const WA = window.WritingAgent;
    const appLLMAdapter = (typeof window !== 'undefined' && typeof window.appLLMAdapter === 'function')
      ? window.appLLMAdapter
      : null;
    const aid = AS && AS.getActiveArticleId ? AS.getActiveArticleId() : null;
    logWritingRuntime('write-article-click', { articleId: aid });

    if (!AS) { setStatus('error'); setErrMsg('The article storage layer is not available. Please reload and try again.'); return; }
    if (!WA || typeof WA.generateArticleDraft !== 'function') { setStatus('error'); setErrMsg('Writing engine script failed to load'); return; }

    /* Hand the brief title/keyword to the editor for its H1, and persist the
       brief so the agent's context is complete. We do NOT clear any existing
       draft up front - the agent overwrites it on success only. */
    try {
      AS.setBrief(aid, form);
      localStorage.setItem('rl.draftSeed', JSON.stringify({
        title: (form.topic || '').trim(),
        primaryKeyword: (form.keyword || '').trim()
      }));
    } catch (e) {}

    try { console.log('write-generation-start', { articleId: aid }); } catch (e) {}

    const writeOptions = { persist: true, canPersist: canGenerateNow, onProgress };
    if (appLLMAdapter) writeOptions.llmAdapter = appLLMAdapter;

    Promise.resolve()
      .then(() => WA.generateArticleDraft(aid, writeOptions))
      .then((res) => {
        if (!mountedRef.current) return;
        if (!canGenerateNow()) {
          setPhase('Read-only mode');
          setErrMsg('Draft generation is unavailable while this Workspace is read-only.');
          setStatus('blocked');
          return;
        }
        if (res && res.success) {
          try { console.log('write-generation-success', { articleId: aid, words: (res.html || '').length, repairAttempts: res.repairAttempts, source: res.source }); } catch (e) {}
          setPhase('Draft ready');
          setStatus('success');
          redirectRef.current = setTimeout(() => {
            try { console.log('write-open-editor', { articleId: aid, via: 'auto' }); } catch (e) {}
            window.location.href = 'Article Editor.html';
          }, 1100);
        } else {
          const publicError = res && res.publicError;
          try {
            console.log('write-generation-error', {
              articleId: aid,
              publicErrorCode: publicError && publicError.code,
              errors: res && res.errors,
              validationIssues: res && res.validation && res.validation.issues
            });
          } catch (e) {}
          setErrMsg(getDraftPublicErrorMessage(res));
          setStatus('error');
        }
      })
      .catch((e) => {
        if (!mountedRef.current || !canGenerateNow()) return;
        try { console.log('write-generation-error', { error: e && e.message }); } catch (_) {}
        setErrMsg(DRAFT_GENERIC_PUBLIC_ERROR);
        setStatus('error');
      });
  };

  const runGeneration = async () => {
    if (!canGenerateNow()) {
      setPhase('Read-only mode');
      setErrMsg('Draft generation is unavailable while this Workspace is read-only.');
      setStatus('blocked');
      return;
    }
    setStatus('writing');
    setErrMsg('');
    setPhase('Preparing article context');
    if (isCloudWorkflow) return runCloudGeneration();
    return runLegacyGeneration();
  };

  const retryCloudDraftSave = () => {
    if (!canMutateNow() || !isCloudWorkflow || status === 'saving') return;
    const pending = cloudUnsavedDraftRef.current;
    const articleId = workflowIdentity && workflowIdentity.articleId;
    const controller = getCloudDraftController();
    if (!pending || !pending.draftResult || !articleId || !controller) return;
    const requestId = cloudSaveRequestRef.current + 1;
    cloudSaveRequestRef.current = requestId;
    setStatus('saving');
    setErrMsg('');
    setPhase('Saving draft');
    controller.retryDraftSave(articleId, pending.draftResult, pending.form || form, {
      cloudClient: window.RankLyxCloudArticles,
      accessClient: window.ClicklyxWorkspaceAccess
    }).then((result) => {
      if (!mountedRef.current || cloudSaveRequestRef.current !== requestId) return;
      handleCloudDraftResult(Object.assign({}, result, { draftResult: pending.draftResult, form: pending.form || form }));
    }).catch((e) => {
      if (!mountedRef.current || cloudSaveRequestRef.current !== requestId) return;
      setPhase('Draft written');
      setErrMsg('The draft was generated but could not be saved. Retry before continuing.');
      setStatus('save-error');
    });
  };

  useEffect(() => {
    mountedRef.current = true;
    if (hasRestoredCloudDraft) {
      cloudUnsavedDraftRef.current = null;
      setPhase('Draft saved');
      setStatus('success');
      scheduleCloudEditorOpen();
      return () => { mountedRef.current = false; if (redirectRef.current) clearTimeout(redirectRef.current); };
    }
    if (ranRef.current) return () => { mountedRef.current = false; if (redirectRef.current) clearTimeout(redirectRef.current); };
    ranRef.current = true;
    runGeneration();
    return () => { mountedRef.current = false; if (redirectRef.current) clearTimeout(redirectRef.current); };
    // eslint-disable-next-line
  }, []);

  useEffect(() => {
    if (!isCloudWorkflow) return undefined;
    const invalidateCloudNavigation = () => {
      cloudNavigationInvalidatedRef.current = true;
      cloudSaveRequestRef.current += 1;
      if (redirectRef.current) clearTimeout(redirectRef.current);
      redirectRef.current = null;
    };
    window.addEventListener('ranklyx:workspace-switching', invalidateCloudNavigation);
    return () => window.removeEventListener('ranklyx:workspace-switching', invalidateCloudNavigation);
  }, [isCloudWorkflow]);

  useEffect(() => {
    if (canGenerateDraft || hasRestoredCloudDraft) return;
    cloudSaveRequestRef.current += 1;
    if (redirectRef.current) clearTimeout(redirectRef.current);
    redirectRef.current = null;
    if (status === 'writing' || status === 'saving') {
      setPhase('Read-only mode');
      setErrMsg('Draft generation is unavailable while this Workspace is read-only.');
      setStatus('blocked');
    }
  }, [canGenerateDraft, hasRestoredCloudDraft, status]);

  useLucide([phase, status, errMsg, isCloudWorkflow]);

  if (status === 'blocked') {
    return (
      <div className="rl-ph" data-screen-label="Draft unavailable" style={{ maxWidth: 560 }}>
        <span className="rl-ph__icon"><i data-lucide="lock"></i></span>
        <h2 className="rl-ph__title">Writing is unavailable</h2>
        <p className="rl-ph__desc" style={{ marginBottom: 18 }}>{errMsg}</p>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <button type="button" className="rl-btn rl-btn--primary" onClick={runGeneration} disabled={!canGenerateDraft} style={{ borderRadius: 10 }}>
            <i data-lucide="sparkles"></i>
            <span>Write article</span>
          </button>
          <button type="button" className="rl-btn rl-btn--ghost" onClick={onBack} style={{ borderRadius: 10 }}>
            <span>Back to Outline</span>
          </button>
        </div>
      </div>);
  }

  if (status === 'save-error') {
    return (
      <div className="rl-ph" data-screen-label="Draft unsaved" style={{ maxWidth: 560 }}>
        <span className="rl-ph__icon" style={{ color: 'var(--rl-danger, #c0392b)' }}><i data-lucide="alert-triangle"></i></span>
        <h2 className="rl-ph__title">Draft written, but not saved</h2>
        <p className="rl-ph__desc" style={{ marginBottom: 8 }}>{errMsg}</p>
        <p className="rl-ph__desc" style={{ marginBottom: 18, color: 'var(--rl-fg-3, #888)' }}>
          The generated draft is still here in this session. Save it before continuing.
        </p>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <button type="button" className="rl-btn rl-btn--primary" onClick={retryCloudDraftSave} disabled={!canMutateDraft} style={{ borderRadius: 10 }}>
            <i data-lucide="refresh-cw"></i>
            <span>Retry draft save</span>
          </button>
          <button type="button" className="rl-btn rl-btn--ghost" onClick={onBack} style={{ borderRadius: 10 }}>
            <span>Back to Outline</span>
          </button>
        </div>
      </div>);
  }

  if (status === 'error') {
    return (
      <div className="rl-ph" data-screen-label="Draft failed" style={{ maxWidth: 560 }}>
        <span className="rl-ph__icon" style={{ color: 'var(--rl-danger, #c0392b)' }}><i data-lucide="alert-triangle"></i></span>
        <h2 className="rl-ph__title">We couldn't finish the draft</h2>
        <p className="rl-ph__desc" style={{ marginBottom: 8 }}>{errMsg}</p>
        <p className="rl-ph__desc" style={{ marginBottom: 18, color: 'var(--rl-fg-3, #888)' }}>
          Your brief, outline, and research notes are all safe. You can try again.
        </p>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <button type="button" className="rl-btn rl-btn--primary" onClick={runGeneration} disabled={!canGenerateDraft} style={{ borderRadius: 10 }}>
            <i data-lucide="refresh-cw"></i>
            <span>Try again</span>
          </button>
          <button type="button" className="rl-btn rl-btn--ghost" onClick={onBack} style={{ borderRadius: 10 }}>
            <span>Back to Outline</span>
          </button>
        </div>
      </div>);
  }

  if (status === 'success') {
    return (
      <div className="rl-ph" data-screen-label="Draft ready" style={{ maxWidth: 560 }}>
        <span className="rl-ph__icon" style={{ color: 'var(--rl-success, #1f8a5b)' }}><i data-lucide="check-circle-2"></i></span>
        <h2 className="rl-ph__title">Your draft is ready</h2>
        {isCloudWorkflow ?
        <p className="rl-ph__desc" style={{ marginBottom: 18 }}>
          The draft was saved to this Workspace. Opening the editor...
        </p> :
        <p className="rl-ph__desc" style={{ marginBottom: 18 }}>
          The article was written from your outline and saved. Opening the editor...
        </p>}
        {!isCloudWorkflow &&
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          <a className="rl-btn rl-btn--primary" href="Article Editor.html" onClick={() => { try { console.log('write-open-editor', { via: 'manual' }); } catch (e) {} }} style={{ borderRadius: 10, textDecoration: 'none' }}>
            <span>Open in editor</span>
            <i data-lucide="arrow-right"></i>
          </a>
          <button type="button" className="rl-btn rl-btn--ghost" onClick={onBack} style={{ borderRadius: 10 }}>
            <span>Back to Outline</span>
          </button>
        </div>}
      </div>);
  }

  return (
    <div className="rl-ph" data-screen-label="Writing article" style={{ maxWidth: 560 }}>
      <span className="rl-ph__icon"><i data-lucide="sparkles"></i></span>
      <h2 className="rl-ph__title">{status === 'saving' ? 'Saving your draft...' : 'Writing your article...'}</h2>
      <p className="rl-ph__desc" style={{ marginBottom: 18 }}>
        {isCloudWorkflow ? 'The AI is turning your outline into a full draft and will save it to this Workspace.' : "The AI is turning your outline into a full draft. You'll be taken to the editor automatically when it's ready."}
      </p>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11, marginBottom: 24 }}>
        <span className="rl-osum__spinner" style={{ borderColor: 'var(--rl-primary-border)', borderTopColor: 'var(--rl-primary)' }}></span>
        <span style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--rl-fg-2)' }} role="status" aria-live="polite">{phase}</span>
      </div>
      <div>
        <button type="button" className="rl-btn rl-btn--ghost" onClick={onBack} style={{ borderRadius: 10 }}>
          <span>Back to Outline</span>
        </button>
      </div>
    </div>);

}

/* ------------------------------------------------------------------ */
/* Placeholder for steps that aren't built yet (Publish) */
function StepPlaceholder({ step, onBack }) {
  const meta = step === 3 ?
  { name: 'Draft', icon: 'pen-line', desc: 'Your full article draft will be written here from the approved outline. The intro block becomes the opening paragraphs - with no visible "Introduction" heading - and the first H2 follows it.' } :
  { name: 'Publish', icon: 'send', desc: 'Review, optimize, and publish your finished article. This step opens once you have a draft.' };

  useLucide([step]);

  return (
    <div className="rl-ph" data-screen-label={meta.name}>
      <span className="rl-ph__icon"><i data-lucide={meta.icon}></i></span>
      <h2 className="rl-ph__title">{meta.name} - coming up next</h2>
      <p className="rl-ph__desc">{meta.desc}</p>
      <button type="button" className="rl-btn rl-btn--secondary" onClick={onBack}>
        <i data-lucide="arrow-left"></i>
        <span>Back to Outline</span>
      </button>
    </div>);

}

/* ------------------------------------------------------------------ */
/* Articles library */
function stripArticleHtml(html) {
  if (!html) return '';
  try {
    if (typeof document !== 'undefined') {
      const node = document.createElement('div');
      node.innerHTML = String(html || '');
      return (node.textContent || node.innerText || '').replace(/\s+/g, ' ').trim();
    }
  } catch (e) {}
  return String(html || '').replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
}

function countArticleWords(html) {
  const text = stripArticleHtml(html);
  const words = text.match(/[A-Za-z0-9]+(?:['-][A-Za-z0-9]+)*/g);
  return words ? words.length : 0;
}

function formatArticleDate(value) {
  if (!value) return 'Not saved yet';
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return 'Not saved yet';
  try {
    return new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric', year: 'numeric' }).format(d);
  } catch (e) {
    return d.toLocaleDateString();
  }
}

function getArticleCreatedDateParts(value) {
  if (!value) return null;
  const d = new Date(value);
  if (Number.isNaN(d.getTime())) return null;
  const year = d.getFullYear();
  const month = d.getMonth() + 1;
  return {
    year,
    month,
    monthKey: `${year}-${String(month).padStart(2, '0')}`
  };
}

function formatArticleMonthLabel(monthKey) {
  const [year, month] = String(monthKey || '').split('-').map((part) => Number(part));
  if (!year || !month) return monthKey;
  try {
    return new Intl.DateTimeFormat(undefined, { month: 'long', year: 'numeric' }).format(new Date(year, month - 1, 1));
  } catch (e) {
    return monthKey;
  }
}

function getCurrentAccountUser() {
  const current = typeof window !== 'undefined' && window.currentUser ? window.currentUser : {};
  const displayName = String(current.fullName || current.displayName || current.name || 'Account').trim() || 'Account';
  const id = String(current.id || current.userId || current.accountId || '').trim();
  const avatarDataUrl = String(current.avatarDataUrl || current.avatarUrl || current.imageUrl || current.profileImageUrl || '').trim();
  return {
    id,
    displayName,
    avatarDataUrl,
    initials: getInitials(displayName, id)
  };
}

function normalizeArticlePerson(person) {
  if (!person || typeof person !== 'object') return null;
  const displayName = String(person.displayName || person.fullName || person.name || person.label || '').trim();
  const id = String(person.id || person.userId || person.accountId || person.email || displayName).trim();
  const avatarDataUrl = String(person.avatarDataUrl || person.avatarUrl || person.imageUrl || person.profileImageUrl || '').trim();
  if (!displayName && !id && !avatarDataUrl) return null;
  return {
    id,
    displayName: displayName || id || 'Unknown writer',
    avatarDataUrl,
    initials: getInitials(displayName || id, id)
  };
}

function getCloudArticleLibrary() {
  return typeof window !== 'undefined' ? window.RankLyxCloudArticleLibrary : null;
}

function resolveArticleOwner(rec) {
  const snapshot = rec && (rec.ownerSnapshot || rec.creatorSnapshot);
  const cloudOwner = normalizeArticlePerson(snapshot && {
    ...snapshot,
    id: rec.ownerId || rec.creatorId || snapshot.userId
  });
  return cloudOwner ||
    normalizeArticlePerson(rec && rec.owner) ||
    normalizeArticlePerson(rec && rec.writer) ||
    normalizeArticlePerson(rec && rec.author) ||
    normalizeArticlePerson(rec && rec.createdBy) ||
    getCurrentAccountUser();
}

function normalizeArticlePostType(rec) {
  const library = getCloudArticleLibrary();
  if (library && typeof library.normalizePostType === 'function') return library.normalizePostType(rec);
  const brief = rec && rec.brief || {};
  const raw = String(rec && rec.postType || brief.postType || brief.contentType || brief.type || '').trim();
  const topic = String((rec && rec.title) || brief.topic || '').toLowerCase();
  const haystack = (raw + ' ' + topic).toLowerCase();
  if (/comparison|alternative| vs | versus /.test(haystack)) return 'Comparison';
  if (/roundup|best |top |list/.test(haystack)) return 'Roundup';
  if (/review/.test(haystack)) return 'Single Review';
  if (/guide|how to|what is|what-is|tutorial|playbook/.test(haystack)) return 'Guide';
  return raw || 'Other';
}

function getArticlePostTypeClass(postType) {
  const normalized = String(postType || '').trim().toLowerCase();
  if (normalized === 'guide') return 'guide';
  if (normalized === 'roundup') return 'roundup';
  if (normalized === 'comparison') return 'comparison';
  if (normalized === 'single review') return 'single-review';
  return 'other';
}

function getArticleStatusLabel(rec) {
  const library = getCloudArticleLibrary();
  if (library && typeof library.statusLabel === 'function') return library.statusLabel(rec);
  const status = String(rec && rec.status || '').toLowerCase();
  if (status === 'published') return 'Published';
  if (status === 'ready' || status === 'review' || status === 'in-review') return 'Ready';
  if (status === 'outline' || status === 'research') return 'In review';
  return 'Draft';
}

function articleHasLibraryValue(rec) {
  const library = getCloudArticleLibrary();
  if (library && typeof library.hasLibraryValue === 'function') return library.hasLibraryValue(rec);
  if (!rec) return false;
  const hasDraft = !!(rec.draft && rec.draft.html);
  const hasOutline = Array.isArray(rec.outline) && rec.outline.length > 0;
  const brief = rec.brief || {};
  const hasBrief = !!(brief.topic || brief.title || brief.keyword || brief.audience || brief.goal);
  return hasDraft || hasOutline || hasBrief;
}

function mapArticleRow(rec) {
  const library = getCloudArticleLibrary();
  if (library && typeof library.mapArticleRow === 'function') {
    return library.mapArticleRow(rec, { countWords: countArticleWords, getInitials });
  }
  const draft = rec.draft || {};
  const brief = rec.brief || {};
  const persistedWordCount = Object.prototype.hasOwnProperty.call(rec, 'wordCount') ? Number(rec.wordCount) : NaN;
  return {
    id: rec.id,
    writer: resolveArticleOwner(rec),
    title: rec.title || draft.title || brief.topic || 'Untitled article',
    keyword: rec.primaryKeyword || brief.primaryKeyword || brief.keyword || '',
    status: getArticleStatusLabel(rec),
    postType: normalizeArticlePostType(rec),
    createdAt: rec.createdAt || '',
    updatedAt: rec.updatedAt || rec.createdAt || '',
    wordCount: Number.isFinite(persistedWordCount) && persistedWordCount >= 0 ? Math.round(persistedWordCount) : countArticleWords(draft.html),
    hasDraft: !!(draft && draft.html),
    hasOutline: Array.isArray(rec.outline) && rec.outline.length > 0,
    article: rec
  };
}
function ArticleLibraryTable({ rows, onOpenArticle }) {
  return (
    <div className="rl-articles__table-wrap">
      <table className="rl-articles__table">
        <thead>
          <tr>
            <th><span className="rl-articles__th"><i data-lucide="user-round"></i><span>Writer</span></span></th>
            <th><span className="rl-articles__th"><i data-lucide="file-text"></i><span>Title</span></span></th>
            <th><span className="rl-articles__th"><i data-lucide="search"></i><span>Primary keyword</span></span></th>
            <th><span className="rl-articles__th"><i data-lucide="circle-dot"></i><span>Status</span></span></th>
            <th><span className="rl-articles__th"><i data-lucide="calendar"></i><span>Updated</span></span></th>
            <th><span className="rl-articles__th"><i data-lucide="folder"></i><span>Post type</span></span></th>
            <th><span className="rl-articles__th"><i data-lucide="align-left"></i><span>Words</span></span></th>
          </tr>
        </thead>
        <tbody>
          {rows.map((row) =>
          <tr key={row.id}>
            <td>
              <div className="rl-articles-writer">
                <span className="rl-articles-writer__avatar" aria-hidden={!row.writer.avatarDataUrl}>
                  {row.writer.avatarDataUrl ? <img src={row.writer.avatarDataUrl} alt={`${row.writer.displayName} profile photo`} /> : row.writer.initials}
                </span>
                <span className="rl-articles-writer__name">{row.writer.displayName}</span>
              </div>
            </td>
            <td>
              <button type="button" className="rl-articles__titlebtn" onClick={() => onOpenArticle && onOpenArticle(row)}>
                {row.title}
              </button>
              {row.article?.websiteSource?.domain && <span className="c5-article-source">{row.article.websiteSource.domain}{row.article.websiteSource.deleted && <span className="c5-deleted">Deleted</span>}</span>}
            </td>
            <td>{row.keyword || 'No keyword'}</td>
            <td><span className={`rl-status-pill rl-status-pill--${row.status.toLowerCase().replace(/\s+/g, '-')}`}>{row.status}</span></td>
            <td>{formatArticleDate(row.updatedAt)}</td>
            <td>
              <span className={`rl-post-type-tag rl-post-type-tag--${getArticlePostTypeClass(row.postType)}`}>
                <span className="rl-post-type-tag__label">{row.postType}</span>
              </span>
            </td>
            <td>{row.wordCount || 'Not drafted'}</td>
          </tr>
          )}
        </tbody>
      </table>
    </div>);
}

function ArticlesPage({ onCreateArticle, onOpenArticle, articleCollection, workspaceAccess, websites }) {
  const websiteFamily = websites ? window.ClicklyxWebsites.briefFamily() : '';
  const [websiteFilter, setWebsiteFilter] = useState({family:websiteFamily, id:''});
  const websiteId = websiteFilter.family === websiteFamily ? websiteFilter.id : '';
  useEffect(() => {setWebsiteFilter({family:websiteFamily, id:''});}, [websiteFamily]);
  const [query, setQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('All');
  const [typeFilter, setTypeFilter] = useState('All');
  const [sortBy, setSortBy] = useState('updated-desc');
  const [sortOpen, setSortOpen] = useState(false);
  const [filterOpen, setFilterOpen] = useState(false);
  const [dateOpen, setDateOpen] = useState(false);
  const [dateDrillYear, setDateDrillYear] = useState(null);
  const [dateFilter, setDateFilter] = useState('all');
  const [searchOpen, setSearchOpen] = useState(false);
  const toolbarRef = useRef(null);
  const searchInputRef = useRef(null);
  const sortOptions = [
  { value: 'updated-desc', label: 'Newest updated', icon: 'calendar-clock' },
  { value: 'created-desc', label: 'Newest created', icon: 'calendar-plus' },
  { value: 'created-asc', label: 'Oldest created', icon: 'calendar-days' },
  { value: 'title-asc', label: 'Title A-Z', icon: 'arrow-down-a-z' }];
  const statusOptions = [
  { value: 'All', icon: 'list' },
  { value: 'Draft', icon: 'file-text' },
  { value: 'In review', icon: 'clock-3' },
  { value: 'Ready', icon: 'circle-check' },
  { value: 'Published', icon: 'globe-2' }];
  const typeOptions = [
  { value: 'All', icon: 'layers-3' },
  { value: 'Guide', icon: 'book-open' },
  { value: 'Roundup', icon: 'list-checks' },
  { value: 'Comparison', icon: 'columns-2' },
  { value: 'Single Review', icon: 'star' },
  { value: 'Other', icon: 'ellipsis' }];
  const activeFilterCount = (statusFilter !== 'All' ? 1 : 0) + (typeFilter !== 'All' ? 1 : 0);
  const dateFilterActive = dateFilter !== 'all';

  useEffect(() => {
    if (!sortOpen && !filterOpen && !dateOpen) return;
    const onDoc = (e) => {if (toolbarRef.current && !toolbarRef.current.contains(e.target)) {setSortOpen(false);setFilterOpen(false);setDateOpen(false);}};
    const onKey = (e) => {if (e.key === 'Escape') {setSortOpen(false);setFilterOpen(false);setDateOpen(false);}};
    document.addEventListener('mousedown', onDoc);
    document.addEventListener('keydown', onKey);
    return () => {document.removeEventListener('mousedown', onDoc);document.removeEventListener('keydown', onKey);};
  }, [sortOpen, filterOpen, dateOpen]);

  useEffect(() => {
    if (searchOpen && searchInputRef.current) searchInputRef.current.focus();
  }, [searchOpen]);

  const collectionStatus = articleCollection && articleCollection.status || 'loading';
  const collectionError = articleCollection && articleCollection.error || '';
  const articleLibrary = getCloudArticleLibrary();
  const loadedArticles = collectionStatus === 'ready' && Array.isArray(articleCollection.articles) ? articleCollection.articles : [];
  const cloudArticles = articleLibrary && typeof articleLibrary.filterCloudArticles === 'function' ?
    articleLibrary.filterCloudArticles(loadedArticles) : [];
  const rows = cloudArticles.filter(articleHasLibraryValue).map(mapArticleRow);
  const historicalWebsites = new Map((websites?.websites || []).map(site => [site.id,{id:site.id,domain:window.ClicklyxWebsites.domain(site),deleted:false}]));
  for(const article of cloudArticles) if(article.websiteSource?.id===article.websiteId && article.websiteSource.domain)
    historicalWebsites.set(article.websiteId,article.websiteSource);
  const websiteRows = rows.filter(row => !websiteId || row.websiteId === websiteId);
  const legacyArticleCount = useMemo(() => {
    try {
      const client = window.RankLyxCloudArticles;
      return client && typeof client.getLegacyLocalArticleCount === 'function' ? client.getLegacyLocalArticleCount() : 0;
    } catch (e) {
      return 0;
    }
  }, []);
  const legacyNotice = articleLibrary && typeof articleLibrary.formatLegacyNotice === 'function' ?
    articleLibrary.formatLegacyNotice(legacyArticleCount) : '';

  useLucide([query, statusFilter, typeFilter, sortBy, sortOpen, filterOpen, dateOpen, dateDrillYear, dateFilter, searchOpen, collectionStatus, legacyArticleCount]);
  const dateMenu = useMemo(() => {
    const yearMap = new Map();
    websiteRows.forEach((row) => {
      const parts = getArticleCreatedDateParts(row.createdAt);
      if (!parts) return;
      if (!yearMap.has(parts.year)) yearMap.set(parts.year, { year: parts.year, count: 0, months: new Map() });
      const bucket = yearMap.get(parts.year);
      bucket.count += 1;
      bucket.months.set(parts.monthKey, (bucket.months.get(parts.monthKey) || 0) + 1);
    });
    const years = Array.from(yearMap.values()).sort((a, b) => b.year - a.year).map((yearBucket) => ({
      year: yearBucket.year,
      count: yearBucket.count,
      months: Array.from(yearBucket.months.entries()).map(([monthKey, count]) => ({
        monthKey,
        count,
        label: formatArticleMonthLabel(monthKey)
      })).sort((a, b) => b.monthKey.localeCompare(a.monthKey))
    }));
    return { total: websiteRows.length, years };
  }, [websiteRows]);
  const selectedYearBucket = dateMenu.years.find((bucket) => bucket.year === dateDrillYear);
  const filtered = articleLibrary && typeof articleLibrary.filterAndSortRows === 'function' ?
    articleLibrary.filterAndSortRows(websiteRows, { query, statusFilter, typeFilter, dateFilter, sortBy }) :
    [];
  const totalLabel = collectionStatus === 'loading' ? 'Loading articles...' :
    collectionStatus === 'error' ? 'Articles unavailable' :
    String(websiteRows.length) + ' ' + (websiteRows.length === 1 ? 'article' : 'articles');
  const canCreateArticle = workspaceAccess && workspaceAccess.canStartArticleWorkflow === true;
  const accessDescriptionId = !canCreateArticle && workspaceAccess && workspaceAccess.noticeMessage ? 'rl-workspace-access-notice' : undefined;

  return (
    <main className="rl-page rl-articles" data-screen-label="Articles">
      <div className="rl-page__inner rl-articles__inner">
        <header className="rl-articles__hd">
          <div>
            <h1 className="rl-articles__title">Articles</h1>
            <p className="rl-articles__sub">Generated drafts and approved outlines saved from AI Writer.</p>
          </div>
        </header>

        {legacyNotice &&
        <div className="rl-articles__legacy-notice" role="note">
          <i data-lucide="info"></i>
          <span>{legacyNotice}</span>
        </div>}

        <div className="rl-articles__utility">
          <span className="rl-articles__count">{totalLabel}</span>
          <div className="rl-articles__controls" aria-label="Article tools" ref={toolbarRef}>
          {websites && <SelectInput key={websiteFamily} id="c5-articles-website" label="Filter by website" icon="globe" className="c5-articles-website"
            value={websiteId} onChange={id=>setWebsiteFilter({family:websiteFamily,id})}
            onOpen={()=>{setSortOpen(false);setFilterOpen(false);setDateOpen(false);setSearchOpen(false);}}
            options={[{value:'',label:'All websites'},...[...historicalWebsites.values()].map(site=>({value:site.id,label:site.domain+(site.deleted?' — Deleted':'')}))]} />}
          <div className="rl-articles__toolwrap">
            <button
              type="button"
              className={`rl-articles-tool ${sortOpen || sortBy !== 'updated-desc' ? 'rl-articles-tool--active' : ''}`}
              aria-label="Sort"
              aria-haspopup="menu"
              aria-expanded={sortOpen}
              onClick={() => {setSortOpen((open) => !open);setFilterOpen(false);setDateOpen(false);setSearchOpen(false);}}>
              <i data-lucide="arrow-down-up"></i>
              <span className="rl-articles-tooltip" role="tooltip">Sort</span>
            </button>
            <div className="rl-articles-popover rl-articles-popover--sort" role="menu" aria-label="Sort articles" aria-hidden={!sortOpen} data-state={sortOpen ? 'open' : 'closed'}>
                {sortOptions.map((opt) =>
              <button
                key={opt.value}
                type="button"
                role="menuitemradio"
                aria-checked={sortBy === opt.value}
                className={`rl-articles-popover__item ${sortBy === opt.value ? 'rl-articles-popover__item--active' : ''}`}
                onClick={() => {setSortBy(opt.value);setSortOpen(false);}}>
                    <i className="rl-articles-popover__icon" data-lucide={opt.icon}></i>
                    <span>{opt.label}</span>
                    <span className="rl-articles-popover__check">
                      {sortBy === opt.value ? '✓' : ''}
                    </span>
                  </button>
              )}
              </div>
          </div>

          <div className="rl-articles__toolwrap">
            <button
              type="button"
              className={`rl-articles-tool ${filterOpen || activeFilterCount ? 'rl-articles-tool--active' : ''}`}
              aria-label="Filter"
              aria-haspopup="dialog"
              aria-expanded={filterOpen}
              onClick={() => {setFilterOpen((open) => !open);setSortOpen(false);setDateOpen(false);setSearchOpen(false);}}>
              <i data-lucide="list-filter"></i>
              {activeFilterCount > 0 && <span className="rl-articles-tool__badge">{activeFilterCount}</span>}
              <span className="rl-articles-tooltip" role="tooltip">Filter</span>
            </button>
            <div className="rl-articles-popover rl-articles-popover--filter" role="dialog" aria-label="Filter articles" aria-hidden={!filterOpen} data-state={filterOpen ? 'open' : 'closed'}>
                <div className="rl-articles-filter">
                  <div className="rl-articles-filter__label">Status</div>
                  <div className="rl-articles-filter__options">
                    {statusOptions.map((opt) =>
                  <button
                    key={opt.value}
                    type="button"
                    className={`rl-articles-filter__option ${statusFilter === opt.value ? 'rl-articles-filter__option--active' : ''}`}
                    aria-pressed={statusFilter === opt.value}
                    onClick={() => setStatusFilter(opt.value)}>
                        <i className="rl-articles-popover__icon" data-lucide={opt.icon}></i>
                        <span>{opt.value}</span>
                        <span className="rl-articles-popover__check">
                          {statusFilter === opt.value ? '✓' : ''}
                        </span>
                      </button>
                  )}
                  </div>
                </div>
                <div className="rl-articles-filter">
                  <div className="rl-articles-filter__label">Post type</div>
                  <div className="rl-articles-filter__options">
                    {typeOptions.map((opt) =>
                  <button
                    key={opt.value}
                    type="button"
                    className={`rl-articles-filter__option ${typeFilter === opt.value ? 'rl-articles-filter__option--active' : ''}`}
                    aria-pressed={typeFilter === opt.value}
                    onClick={() => setTypeFilter(opt.value)}>
                        <i className="rl-articles-popover__icon" data-lucide={opt.icon}></i>
                        <span>{opt.value}</span>
                        <span className="rl-articles-popover__check">
                          {typeFilter === opt.value ? '✓' : ''}
                        </span>
                      </button>
                  )}
                  </div>
                </div>
              </div>
          </div>

          <div className="rl-articles__toolwrap">
            <button
              type="button"
              className={`rl-articles-tool ${dateOpen || dateFilterActive ? 'rl-articles-tool--active' : ''}`}
              aria-label="Filter articles by date"
              aria-haspopup="dialog"
              aria-expanded={dateOpen}
              onClick={() => {setDateOpen((open) => {const next = !open;if (next) setDateDrillYear(null);return next;});setSortOpen(false);setFilterOpen(false);setSearchOpen(false);}}>
              <i data-lucide="calendar-days"></i>
              {dateFilterActive && <span className="rl-articles-tool__badge">1</span>}
              <span className="rl-articles-tooltip" role="tooltip">Date</span>
            </button>
            <div className="rl-articles-popover rl-articles-popover--date" role="dialog" aria-label="Filter articles by date" aria-hidden={!dateOpen} data-state={dateOpen ? 'open' : 'closed'}>
                {!dateDrillYear ?
              <div className="rl-articles-date">
                  <button
                    type="button"
                    className={`rl-articles-popover__item ${dateFilter === 'all' ? 'rl-articles-popover__item--active' : ''}`}
                    onClick={() => {setDateFilter('all');setDateOpen(false);setDateDrillYear(null);}}>
                    <i className="rl-articles-popover__icon" data-lucide="calendar-days"></i>
                    <span>All dates</span>
                    <span className="rl-articles-popover__count">{dateMenu.total}</span>
                    <span className="rl-articles-popover__check">
                      {dateFilter === 'all' ? '✓' : ''}
                    </span>
                  </button>
                  {dateMenu.years.map((bucket) =>
                <button
                  key={bucket.year}
                  type="button"
                  className={`rl-articles-popover__item ${dateFilter === `year:${bucket.year}` || dateFilter.startsWith(`month:${bucket.year}-`) ? 'rl-articles-popover__item--active' : ''}`}
                  onClick={() => setDateDrillYear(bucket.year)}>
                      <i className="rl-articles-popover__icon" data-lucide="calendar"></i>
                      <span>{bucket.year}</span>
                      <span className="rl-articles-popover__count">{bucket.count}</span>
                      <span className="rl-articles-popover__chev"><i data-lucide="chevron-right"></i></span>
                    </button>
                )}
                </div> :
              <div className="rl-articles-date">
                  <div className="rl-articles-date__head">
                    <button type="button" className="rl-articles-date__back" aria-label="Back to years" onClick={() => setDateDrillYear(null)}>
                      <i data-lucide="chevron-left"></i>
                    </button>
                    <span>Date / {dateDrillYear}</span>
                  </div>
                  <button
                    type="button"
                    className={`rl-articles-popover__item ${dateFilter === `year:${dateDrillYear}` ? 'rl-articles-popover__item--active' : ''}`}
                    onClick={() => {setDateFilter(`year:${dateDrillYear}`);setDateOpen(false);}}>
                    <i className="rl-articles-popover__icon" data-lucide="calendar-days"></i>
                    <span>All of {dateDrillYear}</span>
                    <span className="rl-articles-popover__count">{selectedYearBucket ? selectedYearBucket.count : 0}</span>
                    <span className="rl-articles-popover__check">
                      {dateFilter === `year:${dateDrillYear}` ? '✓' : ''}
                    </span>
                  </button>
                  {(selectedYearBucket ? selectedYearBucket.months : []).map((month) =>
                <button
                  key={month.monthKey}
                  type="button"
                  className={`rl-articles-popover__item ${dateFilter === `month:${month.monthKey}` ? 'rl-articles-popover__item--active' : ''}`}
                  onClick={() => {setDateFilter(`month:${month.monthKey}`);setDateOpen(false);}}>
                      <i className="rl-articles-popover__icon" data-lucide="calendar"></i>
                      <span>{month.label}</span>
                      <span className="rl-articles-popover__count">{month.count}</span>
                      <span className="rl-articles-popover__check">
                        {dateFilter === `month:${month.monthKey}` ? '✓' : ''}
                      </span>
                    </button>
                )}
                </div>
              }
              </div>
          </div>

          <div className={`rl-articles-searchbar ${searchOpen ? 'rl-articles-searchbar--open' : ''}`} data-state={searchOpen ? 'open' : 'closed'}>
            <label className="rl-articles-searchbar__field" aria-hidden={!searchOpen}>
                <i data-lucide="search"></i>
                <input
                  ref={searchInputRef}
                  tabIndex={searchOpen ? 0 : -1}
                  value={query}
                  onChange={(e) => setQuery(e.target.value)}
                  onKeyDown={(e) => {if (e.key === 'Escape' && !query) setSearchOpen(false);}}
                  placeholder="Search title or keyword"
                  aria-label="Search title or keyword" />
                {query &&
              <button type="button" className="rl-articles-searchbar__clear" aria-label="Clear search" onClick={() => setQuery('')}>
                    <i data-lucide="x"></i>
                  </button>
              }
              </label>
            <button
              type="button"
              className={`rl-articles-tool ${searchOpen || query ? 'rl-articles-tool--active' : ''}`}
              aria-label="Search"
              aria-expanded={searchOpen}
              onClick={() => {setSearchOpen((open) => !open);setSortOpen(false);setFilterOpen(false);setDateOpen(false);}}>
              <i data-lucide="search"></i>
              <span className="rl-articles-tooltip" role="tooltip">Search</span>
            </button>
          </div>
          </div>
        </div>

        {collectionStatus === 'loading' ?
        <section className="rl-articles__empty" role="status">
          <span className="rl-articles__empty-icon"><i data-lucide="loader-circle"></i></span>
          <h2>Loading articles</h2>
          <p>Fetching this Workspace's saved articles.</p>
        </section> :
        collectionStatus === 'error' ?
        <section className="rl-articles__empty" role="alert">
          <span className="rl-articles__empty-icon"><i data-lucide="cloud-off"></i></span>
          <h2>Articles are unavailable</h2>
          <p>{collectionError || 'This Workspace could not be loaded right now.'}</p>
          <button type="button" className="rl-btn rl-btn--primary" onClick={() => articleCollection && articleCollection.retry && articleCollection.retry()}>
            <i data-lucide="refresh-cw"></i><span>Try again</span>
          </button>
        </section> :
        rows.length === 0 ?
        <section className="rl-articles__empty c5-articles-empty">
          <span className="rl-articles__empty-icon"><i data-lucide="file-text"></i></span>
          <h2>No articles yet</h2>
          <p>Generated drafts will appear here after you create an outline or write an article.</p>
          <button type="button" className="rl-btn rl-btn--primary c5-articles-create" onClick={() => canCreateArticle && onCreateArticle && onCreateArticle()} disabled={!canCreateArticle} aria-describedby={accessDescriptionId}>
            <i data-lucide="plus"></i><span>Create article</span>
          </button>
        </section> :
        filtered.length === 0 ?
        <section className="rl-articles__empty">
          <span className="rl-articles__empty-icon"><i data-lucide="search"></i></span>
          <h2>No matching articles</h2>
          <p>Try a different title, keyword, status, or post type.</p>
        </section> :
        <ArticleLibraryTable rows={filtered} onOpenArticle={onOpenArticle} />}
      </div>
    </main>);
}

/* ------------------------------------------------------------------ */
/* Settings */
const SETTINGS_SECTIONS = [
{ id: 'profile', label: 'Profile' },
{ id: 'workspace', label: 'Workspace' },
{ id: 'billing', label: 'Billing & credits' },
{ id: 'support', label: 'Support' }];
const SETTINGS_SECTION_NAVIGATION_KEY = 'rl-settings-section';

function loadSettingsSectionNavigationRequest() {
  try {
    const section = String(localStorage.getItem(SETTINGS_SECTION_NAVIGATION_KEY) || '').trim();
    localStorage.removeItem(SETTINGS_SECTION_NAVIGATION_KEY);
    return section ? { section: normalizeSettingsSectionId(section), token: Date.now() } : null;
  } catch (error) {
    return null;
  }
}

function normalizeSettingsSectionId(sectionId, sections) {
  const legacySections = { credits: 'billing', notifications: 'profile', 'data-privacy': 'support' };
  const requested = String(sectionId || '').trim();
  const normalized = Object.prototype.hasOwnProperty.call(legacySections, requested) ? legacySections[requested] : requested;
  const available = Array.isArray(sections) && sections.length ? sections : SETTINGS_SECTIONS;
  return available.some((section) => section.id === normalized) ? normalized : available[0].id;
}

function loadProfileSettings() {
  const current = window.currentUser || {};
  const firstName = current.firstName || '';
  const lastName = current.lastName || '';
  const fullName = current.fullName || current.displayName || current.name || [firstName, lastName].filter(Boolean).join(' ') || 'Account';
  const imageUrl = current.imageUrl || current.avatarDataUrl || '';
  return {
    id: current.id || current.userId || '',
    userId: current.userId || current.id || '',
    firstName,
    lastName,
    fullName,
    displayName: current.displayName || fullName,
    name: current.name || firstName || fullName,
    email: current.email || '',
    roleTitle: current.roleTitle || current.title || '',
    avatarDataUrl: imageUrl,
    imageUrl,
    hasImage: !!current.hasImage
  };
}

function normalizeWorkspaceSettings(source) {
  const current = source || {};
  const websiteSource = current.websiteUrl != null ? current.websiteUrl : current.website;
  const website = websiteSource == null ? '' : String(websiteSource);
  const imageUrl = current.imageUrl || current.logoDataUrl || current.logoUrl || '';
  return {
    id: current.id || current.organizationId || '',
    organizationId: current.organizationId || current.id || '',
    name: current.name || 'Workspace',
    membersCount: current.membersCount == null ? null : current.membersCount,
    role: current.role || '',
    description: current.description || '',
    website,
    websiteUrl: website || null,
    industry: current.industry || 'SaaS',
    imageUrl,
    logoDataUrl: imageUrl,
    hasImage: current.hasImage === false ? false : current.hasImage === true ? true : !!imageUrl
  };
}

function loadWorkspaceSettings() {
  return normalizeWorkspaceSettings(window.currentWorkspace || {});
}


function getWorkspaceRoleLabel(role) {
  const normalized = String(role || '').toLowerCase().replace(/^org:/, '');
  if (normalized === 'admin') return 'Administrator';
  if (normalized === 'member' || !normalized) return 'Member';
  return 'Unsupported';
}

function isWorkspaceAdminRole(role) {
  const normalized = String(role || '').toLowerCase().trim();
  return normalized === 'admin' || normalized === 'org:admin';
}

function getWorkspaceCommercialRuntime() {
  return window.RankLyxWorkspaceCommercial || null;
}

function getCreditMetricText(creditState, field) {
  if (!creditState || creditState.status === 'idle' || creditState.status === 'loading') return 'Loading...';
  if (creditState.status !== 'loaded' || !creditState.summary || !creditState.summary.articleGeneration) return 'Unavailable';
  const value = creditState.summary.articleGeneration[field];
  return Number.isSafeInteger(value) && value >= 0 ? String(value) : 'Unavailable';
}

function getCreditStateMessage(creditState) {
  if (!creditState || creditState.status === 'idle' || creditState.status === 'loading') return 'Loading Articles...';
  if (creditState.status === 'loaded') return '';
  return 'Article usage is unavailable right now.';
}

function getCommercialPresentation(commercialState) {
  const runtime = getWorkspaceCommercialRuntime();
  const unavailable = {
    plan: 'Unavailable',
    paymentStatus: 'Unavailable',
    billingCycle: 'Unavailable',
    cadence: 'Unavailable',
    cancellation: 'Unavailable',
    seats: 'Unavailable',
    note: ''
  };
  if (!commercialState || commercialState.status === 'idle' || commercialState.status === 'loading') {
    return { ...unavailable, plan: 'Loading...', paymentStatus: 'Loading...', note: 'Loading billing details...' };
  }
  if (commercialState.status === 'unauthorized') {
    return { ...unavailable, note: 'Billing details are not available for this role.' };
  }
  if (commercialState.status !== 'loaded' || !commercialState.billing) {
    return { ...unavailable, note: 'Billing details are unavailable right now. Credit usage may still be available below.' };
  }
  const billing = commercialState.billing;
  const subscription = billing.subscription || {};
  if (subscription.present !== true) {
    return {
      ...unavailable,
      plan: 'No current subscription',
      paymentStatus: 'No current subscription',
      cancellation: 'Not scheduled',
      note: 'This workspace does not have a current subscription.'
    };
  }
  const catalogResolved = subscription.catalogResolved === true;
  const periodEndLabel = runtime && typeof runtime.formatBillingDate === 'function' ? runtime.formatBillingDate(subscription.currentPeriod && subscription.currentPeriod.end) : '';
  return {
    plan: catalogResolved && billing.plan && billing.plan.displayName ? billing.plan.displayName : 'Plan unavailable',
    paymentStatus: runtime && typeof runtime.formatPaymentStatus === 'function' ? runtime.formatPaymentStatus(subscription.paymentState) : 'Unavailable',
    billingCycle: runtime && typeof runtime.formatBillingCycle === 'function' ? runtime.formatBillingCycle(subscription.currentPeriod) : 'Unavailable',
    cadence: runtime && typeof runtime.formatBillingCadence === 'function' ? runtime.formatBillingCadence(subscription.billingInterval, subscription.billingIntervalCount) : 'Unavailable',
    cancellation: subscription.cancellationScheduled === true ? periodEndLabel ? `Scheduled to end ${periodEndLabel}` : 'Scheduled for period end' : 'Not scheduled',
    seats: catalogResolved && runtime && typeof runtime.formatSeats === 'function' ? runtime.formatSeats(billing.seats) : 'Unavailable',
    note: catalogResolved ? '' : 'Plan and seat details are unavailable for this subscription.'
  };
}

function getCapturedCheckoutReturn() {
  try {
    const runtime = window.ClicklyxCheckoutReturn;
    return runtime && typeof runtime.getCapturedReturn === 'function' ? runtime.getCapturedReturn() : null;
  } catch (e) {
    return null;
  }
}

function useWorkspaceCommercialReads(workspace) {
  const runtime = getWorkspaceCommercialRuntime();
  const [creditState, setCreditState] = useState(() => runtime && typeof runtime.createCreditState === 'function' ? runtime.createCreditState('idle') : { status: 'idle', summary: null, errorCode: '' });
  const [commercialState, setCommercialState] = useState(() => runtime && typeof runtime.createCommercialState === 'function' ? runtime.createCommercialState('hidden') : { status: 'hidden', billing: null, errorCode: '' });
  const coordinatorRef = useRef(null);
  const workspaceId = getWorkspaceMembershipId(workspace);
  const administrator = isWorkspaceAdminRole(workspace && workspace.role);

  if (!coordinatorRef.current && runtime && typeof runtime.createWorkspaceReadCoordinator === 'function') {
    coordinatorRef.current = runtime.createWorkspaceReadCoordinator((endpoint, options) => {
      const auth = window.RankLyxAuth;
      if (!auth || typeof auth.authenticatedFetch !== 'function') {
        return Promise.reject(new Error('Authenticated workspace reads are unavailable.'));
      }
      return auth.authenticatedFetch(endpoint, options);
    });
  }

  const applyUpdate = (update) => {
    if (!update) return;
    if (update.type === 'reset') {
      setCreditState(update.creditState);
      setCommercialState(update.commercialState);
      return;
    }
    if (update.type === 'credits') setCreditState(update.creditState);
    if (update.type === 'commercial') setCommercialState(update.commercialState);
  };

  useEffect(() => {
    const coordinator = coordinatorRef.current;
    if (!coordinator) {
      setCreditState({ status: 'error', summary: null, errorCode: 'workspace_commercial_runtime_unavailable' });
      setCommercialState({ status: administrator ? 'error' : 'hidden', billing: null, errorCode: 'workspace_commercial_runtime_unavailable' });
      return undefined;
    }
    coordinator.load({ workspaceId, isAdministrator: administrator }, applyUpdate);
    return () => coordinator.cancel();
  }, [workspaceId, administrator]);

  useEffect(() => {
    const handleWorkspaceSwitching = () => {
      const coordinator = coordinatorRef.current;
      if (coordinator) coordinator.clear({ isAdministrator: administrator }, applyUpdate);
    };
    window.addEventListener('ranklyx:workspace-switching', handleWorkspaceSwitching);
    return () => window.removeEventListener('ranklyx:workspace-switching', handleWorkspaceSwitching);
  }, [administrator]);

  const refreshCommercial = (expectedWorkspaceId) => {
    const coordinator = coordinatorRef.current;
    if (!coordinator || typeof coordinator.refreshCommercial !== 'function'
      || !administrator || String(expectedWorkspaceId || '') !== String(workspaceId || '')) {
      return Promise.resolve({ stale: true, workspaceId });
    }
    return coordinator.refreshCommercial({ workspaceId, isAdministrator: administrator }, applyUpdate);
  };

  const refreshWorkspaceReads = (expectedWorkspaceId) => {
    const coordinator = coordinatorRef.current;
    if (!coordinator || typeof coordinator.refreshAll !== 'function'
      || !administrator || String(expectedWorkspaceId || '') !== String(workspaceId || '')) {
      return Promise.resolve({ stale: true, workspaceId });
    }
    return coordinator.refreshAll({ workspaceId, isAdministrator: administrator }, applyUpdate);
  };

  return { creditState, commercialState, administrator, refreshCommercial, refreshWorkspaceReads };
}

function SettingsField({ label, hint, children }) {
  return (
    <label className="rl-settings-field">
      <span className="rl-settings-field__label">{label}</span>
      {hint && <span className="rl-settings-field__hint">{hint}</span>}
      {children}
    </label>);
}

const WORKSPACE_WEBSITE_INVALID_MESSAGE = 'Enter a valid website URL beginning with http:// or https://.';

function validateOptionalWebsiteInput(value) {
  const text = String(value || '').trim();
  if (!text) return { valid: true, value: '' };
  try {
    const parsed = new URL(text);
    if (parsed.protocol === 'http:' || parsed.protocol === 'https:') return { valid: true, value: text };
  } catch (error) {}
  return { valid: false, value: text, message: WORKSPACE_WEBSITE_INVALID_MESSAGE };
}

function getSettingsPublicErrorMessage(error, fallback) {
  if (error && error.publicMessage) return error.publicMessage;
  const candidates = [];
  if (Array.isArray(error && error.errors)) candidates.push(...error.errors);
  if (Array.isArray(error)) candidates.push(...error);
  candidates.push(error || {});
  for (const item of candidates) {
    const message = item && (item.longMessage || item.long_message || item.message);
    if (typeof message === 'string' && message.trim()) return message.trim();
  }
  return fallback;
}

function normalizeAccountSecurityStateForUi(state, fallbackEmail) {
  const source = state || {};
  const externalAccounts = Array.isArray(source.externalAccounts) ? source.externalAccounts : [];
  return {
    loaded: true,
    loading: false,
    email: String(source.email || fallbackEmail || '').trim(),
    passwordEnabled: source.passwordEnabled === true,
    totpEnabled: source.totpEnabled === true,
    backupCodeEnabled: source.backupCodeEnabled === true,
    twoFactorEnabled: source.twoFactorEnabled === true,
    mfaFeatureEnabled: source.mfaFeatureEnabled === true,
    currentSessionId: source.currentSessionId ? String(source.currentSessionId) : '',
    externalAccounts: externalAccounts.map((account) => ({
      providerName: normalizeProviderNameForUi(account && account.providerName)
    }))
  };
}

function normalizeProviderNameForUi(value) {
  const text = String(value || '').trim();
  if (!text || !/^[A-Za-z][A-Za-z0-9 ]{0,31}$/.test(text)) return 'Connected provider';
  return text;
}

function formatConnectedProviderText(accounts) {
  const names = (Array.isArray(accounts) ? accounts : []).map((account) => String(account && account.providerName || '').trim()).filter(Boolean);
  const uniqueNames = names.filter((name, index) => names.findIndex((other) => other.toLowerCase() === name.toLowerCase()) === index);
  if (!uniqueNames.length) return '';
  if (uniqueNames.length === 1) return 'Connected with ' + uniqueNames[0];
  if (uniqueNames.length === 2) return 'Connected with ' + uniqueNames[0] + ' and ' + uniqueNames[1];
  return 'Connected with ' + uniqueNames.slice(0, -1).join(', ') + ', and ' + uniqueNames[uniqueNames.length - 1];
}

function createSettingsPublicError(message, code) {
  const error = new Error(message);
  error.publicMessage = message;
  error.code = code || 'settings_security_failed';
  return error;
}

const WORKSPACE_DIRECTORY_PAGE_LIMIT = 20;

function getWorkspaceDirectoryId(source) {
  return String(source && (source.organizationId || source.id) || '').trim();
}

function createWorkspaceDirectoryState(workspaceId) {
  return {
    workspaceId: String(workspaceId || '').trim(),
    loaded: false,
    loading: false,
    loadingMoreMembers: false,
    loadingMoreInvitations: false,
    error: '',
    members: [],
    invitations: [],
    capabilities: {
      canViewMembers: false,
      canManageMembers: false,
      canInviteMembers: false,
      canChangeRoles: false,
      canRemoveMembers: false
    },
    canManageMembers: false,
    invitationsVisible: false,
    role: '',
    roleLabel: 'Member',
    membersPage: { offset: 0, limit: WORKSPACE_DIRECTORY_PAGE_LIMIT, totalCount: 0, hasMore: false, nextOffset: 0 },
    invitationsPage: { offset: 0, limit: WORKSPACE_DIRECTORY_PAGE_LIMIT, totalCount: 0, hasMore: false, nextOffset: 0 }
  };
}

function normalizeWorkspaceDirectoryCapabilities(capabilities) {
  const source = capabilities || {};
  return {
    canViewMembers: source.canViewMembers === true,
    canManageMembers: source.canManageMembers === true,
    canInviteMembers: source.canInviteMembers === true,
    canChangeRoles: source.canChangeRoles === true,
    canRemoveMembers: source.canRemoveMembers === true
  };
}

function normalizeWorkspaceDirectoryRoleLabel(value) {
  const text = String(value || '').trim();
  if (text === 'Administrator' || text === 'Member' || text === 'Unsupported') return text;
  return getWorkspaceRoleLabel(text);
}

function normalizeWorkspaceDirectoryRoleValue(value) {
  const normalized = String(value || '').trim().toLowerCase();
  if (normalized === 'org:admin' || normalized === 'admin') return 'org:admin';
  if (normalized === 'org:member' || normalized === 'member') return 'org:member';
  return 'unsupported';
}

function safeWorkspaceDirectoryImageUrl(value) {
  const text = String(value || '').trim();
  return /^https:\/\//i.test(text) || /^http:\/\//i.test(text) ? text : '';
}

function formatWorkspaceDirectoryDate(value) {
  if (!value) return 'Not available';
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return 'Not available';
  try {
    return new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric', year: 'numeric' }).format(date);
  } catch (error) {
    return date.toLocaleDateString();
  }
}

function normalizeWorkspaceDirectoryPage(page, fallbackOffset, fallbackLimit) {
  const source = page || {};
  const offset = Number.isInteger(source.offset) && source.offset >= 0 ? source.offset : fallbackOffset || 0;
  const limit = Number.isInteger(source.limit) && source.limit > 0 ? source.limit : fallbackLimit || WORKSPACE_DIRECTORY_PAGE_LIMIT;
  const totalCount = Number.isInteger(source.totalCount) && source.totalCount >= 0 ? source.totalCount : 0;
  const nextOffset = Number.isInteger(source.nextOffset) && source.nextOffset >= offset ? source.nextOffset : offset;
  return {
    offset,
    limit,
    totalCount,
    hasMore: source.hasMore === true,
    nextOffset
  };
}

function normalizeWorkspaceDirectoryMemberForUi(member) {
  const source = member || {};
  const emailAddress = String(source.emailAddress || '').trim();
  const displayName = String(source.displayName || emailAddress || 'Workspace member').trim();
  const role = normalizeWorkspaceDirectoryRoleValue(source.role);
  const roleLabel = role === 'unsupported' ? 'Unsupported' : normalizeWorkspaceDirectoryRoleLabel(source.roleLabel || role);
  return {
    membershipId: String(source.membershipId || source.userId || displayName || emailAddress).trim(),
    userId: String(source.userId || '').trim(),
    displayName,
    emailAddress,
    imageUrl: safeWorkspaceDirectoryImageUrl(source.imageUrl),
    initials: getInitials(displayName, emailAddress),
    role,
    roleLabel,
    joinedAt: String(source.joinedAt || '').trim(),
    joinedAtLabel: formatWorkspaceDirectoryDate(source.joinedAt),
    isCurrentUser: source.isCurrentUser === true
  };
}

function normalizeWorkspaceDirectoryInvitationForUi(invitation) {
  const source = invitation || {};
  const emailAddress = String(source.emailAddress || '').trim();
  const createdAt = String(source.createdAt || '').trim();
  const expiresAt = String(source.expiresAt || '').trim();
  return {
    invitationId: String(source.invitationId || emailAddress || createdAt).trim(),
    emailAddress,
    role: String(source.role || '').trim(),
    roleLabel: normalizeWorkspaceDirectoryRoleLabel(source.roleLabel || source.role),
    status: 'pending',
    statusLabel: 'Pending',
    createdAt,
    createdAtLabel: formatWorkspaceDirectoryDate(createdAt),
    expiresAt,
    expiresAtLabel: expiresAt ? formatWorkspaceDirectoryDate(expiresAt) : ''
  };
}

function mergeWorkspaceDirectoryItems(existing, incoming, idKey) {
  const seen = new Set();
  const merged = [];
  [...(Array.isArray(existing) ? existing : []), ...(Array.isArray(incoming) ? incoming : [])].forEach((item) => {
    const id = String(item && item[idKey] || '').trim();
    if (!id || seen.has(id)) return;
    seen.add(id);
    merged.push(item);
  });
  return merged;
}

function normalizeWorkspaceDirectoryPayloadForUi(payload, fallbackLimit) {
  const source = payload || {};
  const capabilities = normalizeWorkspaceDirectoryCapabilities(source.capabilities);
  const members = (Array.isArray(source.members) ? source.members : []).map(normalizeWorkspaceDirectoryMemberForUi);
  const invitations = (Array.isArray(source.invitations) ? source.invitations : []).map(normalizeWorkspaceDirectoryInvitationForUi);
  return {
    workspaceId: String(source.organizationId || '').trim(),
    loaded: true,
    loading: false,
    loadingMoreMembers: false,
    loadingMoreInvitations: false,
    error: '',
    members,
    invitations,
    capabilities,
    canManageMembers: source.canManageMembers === true || capabilities.canManageMembers,
    invitationsVisible: source.invitationsVisible === true,
    role: String(source.role || '').trim(),
    roleLabel: normalizeWorkspaceDirectoryRoleLabel(source.roleLabel || source.role),
    membersPage: normalizeWorkspaceDirectoryPage(source.membersPage, 0, fallbackLimit),
    invitationsPage: normalizeWorkspaceDirectoryPage(source.invitationsPage, 0, fallbackLimit)
  };
}

function buildWorkspaceMembersDirectoryUrl(options) {
  const params = new URLSearchParams();
  params.set('memberOffset', String(options && options.memberOffset || 0));
  params.set('invitationOffset', String(options && options.invitationOffset || 0));
  params.set('limit', String(options && options.limit || WORKSPACE_DIRECTORY_PAGE_LIMIT));
  return '/api/workspace-members?' + params.toString();
}

function parseWorkspaceMembersDirectoryResponse(response) {
  return Promise.resolve(response && typeof response.json === 'function' ? response.json().catch(() => ({})) : {}).then((body) => {
    if (response && response.ok) return body;
    const message = body && body.error && body.error.message ? body.error.message : 'Workspace members could not be loaded right now.';
    const code = body && body.error && body.error.code ? body.error.code : 'workspace_members_unavailable';
    throw createSettingsPublicError(message, code);
  });
}

const WORKSPACE_INVITATION_DEFAULT_ROLE = 'org:member';
const WORKSPACE_INVITATION_ROLE_OPTIONS = [
  { value: 'org:member', label: 'Member', description: 'Can create and edit workspace content.' },
  { value: 'org:admin', label: 'Administrator', description: 'Can manage workspace settings and members.' }
];

function createWorkspaceInvitationFormState() {
  return {
    issuanceRequestId: '',
    emailAddress: '',
    role: WORKSPACE_INVITATION_DEFAULT_ROLE,
    emailError: '',
    error: '',
    submitting: false
  };
}

function getWorkspaceInvitationRoleDescription(role) {
  const option = WORKSPACE_INVITATION_ROLE_OPTIONS.find((item) => item.value === role) || WORKSPACE_INVITATION_ROLE_OPTIONS[0];
  return option.description;
}

function validateWorkspaceInvitationEmailInput(value) {
  const emailAddress = String(value || '').trim().toLowerCase();
  if (!emailAddress || emailAddress.length > 254 || /\s|[\x00-\x1F\x7F]/.test(emailAddress)) {
    return { emailAddress, error: 'Enter a valid email address.' };
  }
  const atIndex = emailAddress.indexOf('@');
  const domain = atIndex >= 0 ? emailAddress.slice(atIndex + 1) : '';
  if (atIndex <= 0 || atIndex !== emailAddress.lastIndexOf('@') || !domain || domain.indexOf('.') === -1) {
    return { emailAddress, error: 'Enter a valid email address.' };
  }
  return { emailAddress, error: '' };
}

function buildWorkspaceInvitationsUrl() {
  return '/api/workspace-invitations';
}

function parseWorkspaceInvitationMutationResponse(response) {
  return Promise.resolve(response && typeof response.json === 'function' ? response.json().catch(() => ({})) : {}).then((body) => {
    if (response && response.ok) return body;
    const message = body && body.error && body.error.message ? body.error.message : 'Workspace invitation could not be updated right now.';
    const code = body && body.error && body.error.code ? body.error.code : 'workspace_invitation_unavailable';
    throw createSettingsPublicError(message, code);
  });
}

function isWorkspaceMemberRoleSupported(role) {
  return role === 'org:admin' || role === 'org:member';
}

function buildWorkspaceMemberMutationUrl() {
  return '/api/workspace-members';
}

function getWorkspaceMemberMutationAuth() {
  const auth = window.RankLyxAuth;
  return auth && typeof auth.authenticatedFetch === 'function' ? auth : null;
}

function isWorkspaceMemberMutationRuntimeAvailable() {
  return !!getWorkspaceMemberMutationAuth();
}

function getWorkspaceMemberRoleSelectValue(member) {
  return member && isWorkspaceMemberRoleSupported(member.role) ? member.role : '';
}

function workspaceMemberRoleOptionExists(role) {
  return WORKSPACE_INVITATION_ROLE_OPTIONS.some((option) => option.value === role);
}

function getWorkspaceMemberRoleSelectLabel(role) {
  const option = WORKSPACE_INVITATION_ROLE_OPTIONS.find((item) => item.value === role);
  return option ? option.label : '';
}

function canShowWorkspaceMemberRoleControl(member, canChangeRoles, runtimeAvailable) {
  return canChangeRoles === true && runtimeAvailable === true && !!member && member.isCurrentUser !== true && isWorkspaceMemberRoleSupported(member.role);
}

function canShowWorkspaceMemberRemoveControl(member, canRemoveMembers, runtimeAvailable) {
  return canRemoveMembers === true && runtimeAvailable === true && !!member && member.isCurrentUser !== true && isWorkspaceMemberRoleSupported(member.role);
}

function normalizeWorkspaceMemberRoleRequest(role) {
  return role === 'org:admin' ? 'org:admin' : 'org:member';
}

function getWorkspaceMemberRoleChange(member, role) {
  const nextRole = normalizeWorkspaceMemberRoleRequest(role);
  return {
    nextRole,
    shouldSubmit: !!(member && member.membershipId && member.isCurrentUser !== true && isWorkspaceMemberRoleSupported(member.role) && nextRole !== member.role)
  };
}

function buildWorkspaceMemberRoleMutationOptions(membershipId, nextRole) {
  return {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ membershipId, role: nextRole })
  };
}

function parseWorkspaceMemberMutationResponse(response) {
  return Promise.resolve(response && typeof response.json === 'function' ? response.json().catch(() => ({})) : {}).then((body) => {
    if (response && response.ok) return body;
    const message = body && body.error && body.error.message ? body.error.message : 'Workspace member could not be updated right now.';
    const code = body && body.error && body.error.code ? body.error.code : 'workspace_member_unavailable';
    throw createSettingsPublicError(message, code);
  });
}
function isReverificationRequiredSettingsError(error) {
  if (!error) return false;
  if (error.code === 'session_reverification_required' || error.reverificationRequired === true) return true;
  const errors = Array.isArray(error.errors) ? error.errors : [];
  return errors.some((item) => item && item.code === 'session_reverification_required');
}

function getAccountSecurityAuth() {
  const auth = window.RankLyxAuth;
  if (!auth) throw createSettingsPublicError('Account security settings are unavailable right now.', 'account_security_unavailable');
  return auth;
}

function isSupportedFirstVerificationFactor(factor) {
  return factor && (factor.strategy === 'password' || factor.strategy === 'email_code' && factor.emailAddressId);
}

function isSupportedSecondVerificationFactor(factor) {
  return factor && (factor.strategy === 'totp' || factor.strategy === 'backup_code');
}

function buildLocalTotpQrSvg(uri) {
  if (!uri) throw createSettingsPublicError('Authenticator-app security is not available for this environment yet.', 'totp_uri_missing');
  if (typeof window.qrcode !== 'function') throw createSettingsPublicError('Authenticator-app security is not available for this environment yet.', 'qr_renderer_unavailable');
  const qr = window.qrcode(0, 'M');
  qr.addData(uri);
  qr.make();
  return qr.createSvgTag({ cellSize: 5, margin: 3, scalable: true });
}

function normalizeOneTimeCodes(codes) {
  return (Array.isArray(codes) ? codes : []).map((code) => String(code || '').trim()).filter(Boolean);
}

function copySensitiveText(text, onSuccess, onError) {
  if (!navigator.clipboard || typeof navigator.clipboard.writeText !== 'function') {
    onError('Copy is unavailable in this browser.');
    return;
  }
  navigator.clipboard.writeText(text).then(() => onSuccess()).catch(() => onError('Copy failed. Select the text and copy it manually.'));
}

function trapFocusInDialog(event, container) {
  if (event.key !== 'Tab' || !container) return;
  const focusable = Array.from(container.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')).filter((el) => !el.disabled && el.getAttribute('aria-hidden') !== 'true');
  if (!focusable.length) return;
  const first = focusable[0];
  const last = focusable[focusable.length - 1];
  if (event.shiftKey && document.activeElement === first) {
    event.preventDefault();
    last.focus();
  } else if (!event.shiftKey && document.activeElement === last) {
    event.preventDefault();
    first.focus();
  }
}

function AccountReverificationDialog({ request, onCancel, onComplete }) {
  const [verification, setVerification] = useState(null);
  const [phase, setPhase] = useState('loading');
  const [selectedFirstStrategy, setSelectedFirstStrategy] = useState('');
  const [selectedEmailAddressId, setSelectedEmailAddressId] = useState('');
  const [selectedSecondStrategy, setSelectedSecondStrategy] = useState('');
  const [password, setPassword] = useState('');
  const [emailCode, setEmailCode] = useState('');
  const [secondCode, setSecondCode] = useState('');
  const [emailPrepared, setEmailPrepared] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [notice, setNotice] = useState('');
  const dialogRef = useRef(null);
  const initialFocusRef = useRef(null);
  const previousFocusRef = useRef(null);
  const requestRef = useRef(0);

  const clearVerificationFields = () => {
    setPassword('');
    setEmailCode('');
    setSecondCode('');
  };
  const supportedFirstFactors = (verification && verification.supportedFirstFactors || []).filter(isSupportedFirstVerificationFactor);
  const supportedSecondFactors = (verification && verification.supportedSecondFactors || []).filter(isSupportedSecondVerificationFactor);
  const selectedFirstFactor = supportedFirstFactors.find((factor) => factor.strategy === selectedFirstStrategy && (factor.strategy !== 'email_code' || factor.emailAddressId === selectedEmailAddressId)) || supportedFirstFactors[0] || null;
  const selectedSecondFactor = supportedSecondFactors.find((factor) => factor.strategy === selectedSecondStrategy) || supportedSecondFactors[0] || null;

  const chooseFirstFactor = (factor) => {
    setSelectedFirstStrategy(factor.strategy);
    setSelectedEmailAddressId(factor.emailAddressId || '');
    setEmailPrepared(false);
    setEmailCode('');
    setPassword('');
    setError('');
    setNotice('');
  };
  const handleVerificationResult = (result) => {
    setVerification(result || null);
    if (result && result.status === 'complete') {
      clearVerificationFields();
      onComplete();
      return;
    }
    if (result && result.status === 'needs_second_factor') {
      const nextSecond = (result.supportedSecondFactors || []).filter(isSupportedSecondVerificationFactor)[0];
      setSelectedSecondStrategy(nextSecond ? nextSecond.strategy : '');
      setPhase('second');
      setSecondCode('');
      return;
    }
    setPhase('first');
  };
  useEffect(() => {
    if (!request) return undefined;
    const requestId = requestRef.current + 1;
    requestRef.current = requestId;
    previousFocusRef.current = document.activeElement;
    setVerification(null);
    setPhase('loading');
    setError('');
    setNotice('');
    clearVerificationFields();
    setSelectedFirstStrategy('');
    setSelectedEmailAddressId('');
    setSelectedSecondStrategy('');
    setEmailPrepared(false);
    setBusy(true);
    Promise.resolve().then(() => {
      const auth = getAccountSecurityAuth();
      if (typeof auth.startSessionVerification !== 'function') throw createSettingsPublicError('We could not confirm your identity. Please try again.', 'session_verification_unavailable');
      return auth.startSessionVerification({ level: 'multi_factor' });
    }).then((result) => {
      if (requestRef.current !== requestId) return;
      const first = (result.supportedFirstFactors || []).filter(isSupportedFirstVerificationFactor)[0];
      const second = (result.supportedSecondFactors || []).filter(isSupportedSecondVerificationFactor)[0];
      setSelectedFirstStrategy(first ? first.strategy : '');
      setSelectedEmailAddressId(first && first.emailAddressId || '');
      setSelectedSecondStrategy(second ? second.strategy : '');
      handleVerificationResult(result);
    }).catch((startError) => {
      if (requestRef.current !== requestId) return;
      setPhase('first');
      setError(getSettingsPublicErrorMessage(startError, 'We could not confirm your identity. Please try again.'));
    }).finally(() => {
      if (requestRef.current === requestId) setBusy(false);
    });
    const focusTimer = window.setTimeout(() => {
      if (initialFocusRef.current) initialFocusRef.current.focus();
    }, 0);
    return () => {
      window.clearTimeout(focusTimer);
      clearVerificationFields();
      const previous = previousFocusRef.current;
      if (previous && typeof previous.focus === 'function') previous.focus();
    };
  }, [request && request.token]);
  useEffect(() => {
    if (!request) return undefined;
    const handleKeyDown = (event) => {
      if (event.key === 'Escape' && !busy) {
        clearVerificationFields();
        onCancel();
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [request, busy, onCancel]);
  if (!request) return null;

  const sendEmailCode = () => {
    if (!selectedFirstFactor || busy) return;
    setBusy(true);
    setError('');
    setNotice('');
    Promise.resolve().then(() => {
      const auth = getAccountSecurityAuth();
      return auth.prepareFirstFactorVerification({
        strategy: 'email_code',
        emailAddressId: selectedFirstFactor.emailAddressId
      });
    }).then((result) => {
      setVerification(result || verification);
      setEmailPrepared(true);
      setEmailCode('');
      setNotice('Code sent to ' + (selectedFirstFactor.safeIdentifier || 'your email address') + '.');
    }).catch((sendError) => {
      setError(getSettingsPublicErrorMessage(sendError, 'We could not send a verification code.'));
    }).finally(() => setBusy(false));
  };
  const verifyFirstFactor = (event) => {
    event.preventDefault();
    if (!selectedFirstFactor || busy) return;
    if (selectedFirstFactor.strategy === 'password' && !password) { setError('Enter your password.'); return; }
    if (selectedFirstFactor.strategy === 'email_code' && !emailCode) { setError('Enter the verification code.'); return; }
    setBusy(true);
    setError('');
    setNotice('');
    Promise.resolve().then(() => {
      const auth = getAccountSecurityAuth();
      if (selectedFirstFactor.strategy === 'password') {
        return auth.attemptFirstFactorVerification({ strategy: 'password', password });
      }
      return auth.attemptFirstFactorVerification({ strategy: 'email_code', code: emailCode });
    }).then(handleVerificationResult).catch((verifyError) => {
      setError(getSettingsPublicErrorMessage(verifyError, 'We could not verify that code.'));
    }).finally(() => setBusy(false));
  };
  const verifySecondFactor = (event) => {
    event.preventDefault();
    if (!selectedSecondFactor || busy) return;
    if (!secondCode) { setError(selectedSecondFactor.strategy === 'backup_code' ? 'Enter a recovery code.' : 'Enter your authenticator code.'); return; }
    setBusy(true);
    setError('');
    setNotice('');
    Promise.resolve().then(() => {
      const auth = getAccountSecurityAuth();
      return auth.attemptSecondFactorVerification({ strategy: selectedSecondFactor.strategy, code: secondCode });
    }).then((result) => {
      if (!result || result.status !== 'complete') {
        setVerification(result || verification);
        throw createSettingsPublicError('We could not complete identity confirmation. Please try again.', 'session_verification_incomplete');
      }
      handleVerificationResult(result);
    }).catch((verifyError) => {
      setError(getSettingsPublicErrorMessage(verifyError, 'We could not verify that code.'));
    }).finally(() => setBusy(false));
  };
  const unsupported = phase !== 'loading' && ((phase === 'first' && !supportedFirstFactors.length) || (phase === 'second' && !supportedSecondFactors.length));
  return (
    <div className='rl-settings-modal-scrim rl-settings-modal-scrim--confirm' onMouseDown={busy ? undefined : () => { clearVerificationFields(); onCancel(); }}>
      <div ref={dialogRef} className='rl-settings-modal rl-settings-reverify-modal' role='dialog' aria-modal='true' aria-labelledby='settings-reverify-title' onMouseDown={(event) => event.stopPropagation()} onKeyDown={(event) => trapFocusInDialog(event, dialogRef.current)}>
        <button ref={initialFocusRef} type='button' className='rl-settings-modal__close' onClick={() => { clearVerificationFields(); onCancel(); }} aria-label='Close identity confirmation' disabled={busy}><i data-lucide='x'></i></button>
        <div className='rl-settings-modal__head'>
          <span className='rl-settings-modal__icon' aria-hidden='true'><i data-lucide='shield-check'></i></span>
          <h2 id='settings-reverify-title'>Confirm it&apos;s you</h2>
          <p>For your security, confirm your identity before continuing.</p>
        </div>
        {phase === 'loading' && <p className='rl-settings-empty' role='status'>Preparing identity confirmation...</p>}
        {unsupported && <p className='rl-settings-dialog-error' role='alert'>This verification method is not supported in ClickLyx yet. Please contact support.</p>}
        {phase === 'first' && supportedFirstFactors.length > 0 &&
        <form className='rl-settings-modal__body' onSubmit={verifyFirstFactor}>
          {supportedFirstFactors.length > 1 &&
          <div className='rl-settings-factor-list' role='group' aria-label='Verification methods'>
            {supportedFirstFactors.map((factor) =>
            <button key={factor.strategy + (factor.emailAddressId || '')} type='button' className={'rl-settings-factor-choice ' + (selectedFirstFactor === factor ? 'rl-settings-factor-choice--active' : '')} onClick={() => chooseFirstFactor(factor)} disabled={busy}>{factor.strategy === 'password' ? 'Password' : 'Email verification code'}</button>)}
          </div>}
          {selectedFirstFactor && selectedFirstFactor.strategy === 'password' &&
          <label className='rl-settings-dialog-field' htmlFor='settings-reverify-password'>
            <span>Password</span>
            <input id='settings-reverify-password' className='rl-input' type='password' autoComplete='current-password' value={password} onChange={(event) => setPassword(event.target.value)} />
          </label>}
          {selectedFirstFactor && selectedFirstFactor.strategy === 'email_code' &&
          <div className='rl-settings-code-stack'>
            <p className='rl-settings-helper'>Use the code sent to {selectedFirstFactor.safeIdentifier || 'your email address'}.</p>
            {emailPrepared &&
            <label className='rl-settings-dialog-field' htmlFor='settings-reverify-email-code'>
              <span>Email verification code</span>
              <input id='settings-reverify-email-code' className='rl-input' type='text' inputMode='numeric' autoComplete='one-time-code' value={emailCode} onChange={(event) => setEmailCode(event.target.value)} />
            </label>}
          </div>}
          {error && <p className='rl-settings-dialog-error' role='alert'>{error}</p>}
          {notice && <p className='rl-settings-dialog-notice' role='status'>{notice}</p>}
          <div className='rl-settings-modal__actions'>
            <button type='button' className='rl-btn rl-btn--secondary' onClick={() => { clearVerificationFields(); onCancel(); }} disabled={busy}>Cancel</button>
            {selectedFirstFactor && selectedFirstFactor.strategy === 'email_code' && !emailPrepared && <button type='button' className='rl-btn rl-btn--primary' onClick={sendEmailCode} disabled={busy}>{busy ? 'Sending...' : 'Send code'}</button>}
            {selectedFirstFactor && selectedFirstFactor.strategy === 'email_code' && emailPrepared && <button type='button' className='rl-btn rl-btn--secondary' onClick={sendEmailCode} disabled={busy}>{busy ? 'Sending...' : 'Send another code'}</button>}
            {(selectedFirstFactor && selectedFirstFactor.strategy === 'password' || selectedFirstFactor && selectedFirstFactor.strategy === 'email_code' && emailPrepared) && <button type='submit' className='rl-btn rl-btn--primary' disabled={busy}>{busy ? 'Verifying...' : selectedFirstFactor.strategy === 'password' ? 'Verify' : 'Verify code'}</button>}
          </div>
        </form>}
        {phase === 'second' && supportedSecondFactors.length > 0 &&
        <form className='rl-settings-modal__body' onSubmit={verifySecondFactor}>
          <label className='rl-settings-dialog-field' htmlFor='settings-reverify-second-code'>
            <span>{selectedSecondFactor && selectedSecondFactor.strategy === 'backup_code' ? 'Recovery code' : 'Authenticator code'}</span>
            <input id='settings-reverify-second-code' className='rl-input' type='text' inputMode={selectedSecondFactor && selectedSecondFactor.strategy === 'backup_code' ? 'text' : 'numeric'} autoComplete='one-time-code' value={secondCode} onChange={(event) => setSecondCode(event.target.value)} />
          </label>
          {supportedSecondFactors.some((factor) => factor.strategy === 'backup_code') && selectedSecondFactor && selectedSecondFactor.strategy !== 'backup_code' &&
          <button type='button' className='rl-settings-inline-link' onClick={() => { setSelectedSecondStrategy('backup_code'); setSecondCode(''); setError(''); }} disabled={busy}>Use a recovery code</button>}
          {supportedSecondFactors.some((factor) => factor.strategy === 'totp') && selectedSecondFactor && selectedSecondFactor.strategy === 'backup_code' &&
          <button type='button' className='rl-settings-inline-link' onClick={() => { setSelectedSecondStrategy('totp'); setSecondCode(''); setError(''); }} disabled={busy}>Use an authenticator code</button>}
          {error && <p className='rl-settings-dialog-error' role='alert'>{error}</p>}
          <div className='rl-settings-modal__actions'>
            <button type='button' className='rl-btn rl-btn--secondary' onClick={() => { clearVerificationFields(); onCancel(); }} disabled={busy}>Cancel</button>
            <button type='submit' className='rl-btn rl-btn--primary' disabled={busy}>{busy ? 'Verifying...' : 'Verify code'}</button>
          </div>
        </form>}
      </div>
    </div>);
}
function AccountMfaDialog({ open, accountSecurity, runSensitiveAction, onClose, onSecurityState, onNotice, onError, onRequestRemove }) {
  const [step, setStep] = useState('manage');
  const [manualKey, setManualKey] = useState('');
  const [qrSvg, setQrSvg] = useState('');
  const [verifyCode, setVerifyCode] = useState('');
  const [oneTimeCodes, setOneTimeCodes] = useState([]);
  const [savedCodes, setSavedCodes] = useState(false);
  const [recoveryMode, setRecoveryMode] = useState('setup');
  const [regenerateConfirm, setRegenerateConfirm] = useState(false);
  const [closeWarning, setCloseWarning] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [notice, setNotice] = useState('');
  const dialogRef = useRef(null);
  const firstButtonRef = useRef(null);
  const previousFocusRef = useRef(null);
  const hasTotp = accountSecurity && accountSecurity.totpEnabled === true;
  const hasRecoveryCodes = accountSecurity && accountSecurity.backupCodeEnabled === true;

  const clearMfaSecrets = () => {
    setManualKey('');
    setQrSvg('');
    setVerifyCode('');
    setOneTimeCodes([]);
    setSavedCodes(false);
    setCloseWarning(false);
    setRegenerateConfirm(false);
  };
  const finishClose = () => {
    if (busy) return;
    clearMfaSecrets();
    setError('');
    setNotice('');
    onClose();
  };
  const requestClose = () => {
    if (busy) return;
    if (step === 'recovery' && oneTimeCodes.length && !savedCodes) {
      setCloseWarning(true);
      return;
    }
    finishClose();
  };
  useEffect(() => {
    if (!open) return undefined;
    previousFocusRef.current = document.activeElement;
    setStep(hasTotp ? 'manage' : 'intro');
    clearMfaSecrets();
    setError('');
    setNotice('');
    const timer = window.setTimeout(() => { if (firstButtonRef.current) firstButtonRef.current.focus(); }, 0);
    return () => {
      window.clearTimeout(timer);
      clearMfaSecrets();
      const previous = previousFocusRef.current;
      if (previous && typeof previous.focus === 'function') previous.focus();
    };
  }, [open]);
  useEffect(() => {
    if (!open) return undefined;
    const handleKeyDown = (event) => {
      if (event.key === 'Escape' && !busy) requestClose();
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [open, busy, step, oneTimeCodes, savedCodes]);
  if (!open) return null;

  const startSetup = () => {
    if (busy) return;
    if (manualKey && qrSvg) {
      setVerifyCode('');
      setError('');
      setNotice('');
      setStep('scan');
      return;
    }
    let auth;
    try {
      auth = getAccountSecurityAuth();
      if (typeof auth.createCurrentUserTOTP !== 'function' || typeof window.qrcode !== 'function') throw createSettingsPublicError('Authenticator-app security is not available for this environment yet.', 'totp_unavailable');
    } catch (setupError) {
      setError(getSettingsPublicErrorMessage(setupError, 'Authenticator-app security is not available for this environment yet.'));
      return;
    }
    setBusy(true);
    setError('');
    setNotice('');
    runSensitiveAction(() => auth.createCurrentUserTOTP()).then((totp) => {
      const nextUri = String(totp && totp.uri || '');
      const nextKey = String(totp && totp.secret || '');
      if (!nextUri || !nextKey) throw createSettingsPublicError('Authenticator-app security is not available for this environment yet.', 'totp_unavailable');
      setQrSvg(buildLocalTotpQrSvg(nextUri));
      setManualKey(nextKey);
      setOneTimeCodes(normalizeOneTimeCodes(totp && totp.backupCodes));
      setVerifyCode('');
      setStep('scan');
    }).catch((setupError) => {
      const message = getSettingsPublicErrorMessage(setupError, 'Authenticator-app security is not available for this environment yet.');
      setError(message);
      onError(message);
    }).finally(() => setBusy(false));
  };
  const verifySetupCode = (event) => {
    event.preventDefault();
    if (busy) return;
    const code = String(verifyCode || '').trim();
    if (!/^\d{6}$/.test(code)) { setError('Enter the six-digit code from your authenticator app.'); return; }
    setBusy(true);
    setError('');
    setNotice('');
    const auth = getAccountSecurityAuth();
    runSensitiveAction(() => auth.verifyCurrentUserTOTP({ code })).then((result) => {
      const confirmedState = result && result.accountSecurity;
      if (!confirmedState || confirmedState.totpEnabled !== true) throw createSettingsPublicError('Multi-factor authentication was not confirmed. Please try again.', 'totp_not_confirmed');
      let codes = normalizeOneTimeCodes(result && result.totp && result.totp.backupCodes);
      if (!codes.length) codes = normalizeOneTimeCodes(oneTimeCodes);
      if (!codes.length && confirmedState.backupCodeEnabled !== true) {
        return runSensitiveAction(() => auth.createCurrentUserBackupCode()).then((backupResult) => {
          const backupState = backupResult && backupResult.accountSecurity || confirmedState;
          const backupCodes = normalizeOneTimeCodes(backupResult && backupResult.codes);
          if (!backupCodes.length) throw createSettingsPublicError('Recovery codes could not be shown. Regenerate them from Manage MFA before relying on recovery access.', 'backup_codes_missing');
          onSecurityState(backupState);
          setOneTimeCodes(backupCodes);
          setRecoveryMode('setup');
          setSavedCodes(false);
          setVerifyCode('');
          setStep('recovery');
          return null;
        });
      }
      if (!codes.length) throw createSettingsPublicError('Recovery codes could not be shown. Regenerate them from Manage MFA before relying on recovery access.', 'backup_codes_missing');
      onSecurityState(confirmedState);
      setOneTimeCodes(codes);
      setRecoveryMode('setup');
      setSavedCodes(false);
      setVerifyCode('');
      setStep('recovery');
      return null;
    }).catch((verifyError) => {
      setError(getSettingsPublicErrorMessage(verifyError, 'That authenticator code could not be verified.'));
    }).finally(() => setBusy(false));
  };
  const regenerateRecoveryCodes = () => {
    if (busy) return;
    setBusy(true);
    setError('');
    setNotice('');
    const auth = getAccountSecurityAuth();
    runSensitiveAction(() => auth.createCurrentUserBackupCode()).then((result) => {
      const codes = normalizeOneTimeCodes(result && result.codes);
      if (!codes.length) throw createSettingsPublicError('Recovery codes could not be shown. Please try again.', 'backup_codes_missing');
      onSecurityState(result && result.accountSecurity || accountSecurity);
      setOneTimeCodes(codes);
      setRecoveryMode('regenerate');
      setSavedCodes(false);
      setRegenerateConfirm(false);
      setStep('recovery');
      setNotice('Recovery codes regenerated.');
    }).catch((regenError) => {
      setError(getSettingsPublicErrorMessage(regenError, 'Recovery codes could not be created right now.'));
    }).finally(() => setBusy(false));
  };
  const finishRecoveryStep = () => {
    if (!savedCodes || busy) return;
    const message = recoveryMode === 'regenerate' ? 'Recovery codes regenerated.' : 'Multi-factor authentication enabled.';
    clearMfaSecrets();
    onNotice(message);
    onClose();
  };
  const copyManualKey = () => copySensitiveText(manualKey, () => setNotice('Setup key copied.'), setError);
  const copyAllCodes = () => copySensitiveText(oneTimeCodes.join('\n'), () => setNotice('Recovery codes copied.'), setError);

  return (
    <div className='rl-settings-modal-scrim' onMouseDown={requestClose}>
      <div ref={dialogRef} className='rl-settings-modal rl-settings-mfa-modal' role='dialog' aria-modal='true' aria-labelledby='settings-mfa-title' onMouseDown={(event) => event.stopPropagation()} onKeyDown={(event) => trapFocusInDialog(event, dialogRef.current)}>
        <button type='button' className='rl-settings-modal__close' onClick={requestClose} aria-label='Close multi-factor authentication' disabled={busy}><i data-lucide='x'></i></button>
        <div className='rl-settings-modal__head'>
          <span className='rl-settings-modal__icon' aria-hidden='true'><i data-lucide='shield-check'></i></span>
          <h2 id='settings-mfa-title'>{step === 'manage' ? 'Manage multi-factor authentication' : step === 'recovery' ? 'Save your recovery codes' : 'Set up multi-factor authentication'}</h2>
          <p>{step === 'manage' ? 'Review your authenticator app and recovery-code settings.' : step === 'recovery' ? 'Each recovery code can be used once if you cannot access your authenticator app.' : 'Use an authenticator app to create a security code when you sign in.'}</p>
        </div>
        {step === 'intro' &&
        <div className='rl-settings-modal__body'>
          <p className='rl-settings-helper'>Use Google Authenticator, Microsoft Authenticator, 1Password, or another compatible app.</p>
          {error && <p className='rl-settings-dialog-error' role='alert'>{error}</p>}
          <div className='rl-settings-modal__actions'>
            <button type='button' className='rl-btn rl-btn--secondary' onClick={requestClose} disabled={busy}>Cancel</button>
            <button ref={firstButtonRef} type='button' className='rl-btn rl-btn--primary' onClick={startSetup} disabled={busy}>{busy ? 'Preparing...' : 'Continue'}</button>
          </div>
        </div>}
        {step === 'scan' &&
        <form className='rl-settings-modal__body' onSubmit={verifySetupCode}>
          <div className='rl-settings-qr-panel' aria-label='Authenticator app QR code' dangerouslySetInnerHTML={{ __html: qrSvg }}></div>
          <div className='rl-settings-secret-row'>
            <span>Manual setup key</span>
            <code>{manualKey}</code>
            <button type='button' className='rl-btn rl-btn--secondary' onClick={copyManualKey} disabled={busy}>Copy key</button>
          </div>
          <p className='rl-settings-helper'>Add this account to your authenticator app, then enter the six-digit code from the app.</p>
          <label className='rl-settings-dialog-field' htmlFor='settings-mfa-code'>
            <span>Authenticator code</span>
            <input id='settings-mfa-code' className='rl-input' type='text' inputMode='numeric' autoComplete='one-time-code' value={verifyCode} onChange={(event) => setVerifyCode(event.target.value)} />
          </label>
          {error && <p className='rl-settings-dialog-error' role='alert'>{error}</p>}
          {notice && <p className='rl-settings-dialog-notice' role='status'>{notice}</p>}
          <div className='rl-settings-modal__actions'>
            <button type='button' className='rl-btn rl-btn--secondary' onClick={() => setStep('intro')} disabled={busy}>Back</button>
            <button type='submit' className='rl-btn rl-btn--primary' disabled={busy}>{busy ? 'Verifying...' : 'Verify code'}</button>
          </div>
        </form>}
        {step === 'manage' &&
        <div className='rl-settings-modal__body'>
          <div className='rl-settings-mfa-status-list'>
            <div><strong>Authenticator app</strong><span>Enabled</span></div>
            <div><strong>Recovery codes</strong><span>{hasRecoveryCodes ? 'Created' : 'Not created'}</span></div>
          </div>
          {regenerateConfirm ?
          <div className='rl-settings-warning-box' role='alert'>
            <p>Creating new recovery codes will immediately invalidate your existing codes.</p>
            <div className='rl-settings-modal__actions'>
              <button type='button' className='rl-btn rl-btn--secondary' onClick={() => setRegenerateConfirm(false)} disabled={busy}>Cancel</button>
              <button type='button' className='rl-btn rl-btn--primary' onClick={regenerateRecoveryCodes} disabled={busy}>{busy ? 'Creating...' : 'Create new codes'}</button>
            </div>
          </div> :
          <React.Fragment>
            {error && <p className='rl-settings-dialog-error' role='alert'>{error}</p>}
            {notice && <p className='rl-settings-dialog-notice' role='status'>{notice}</p>}
            <div className='rl-settings-modal__actions'>
              <button ref={firstButtonRef} type='button' className='rl-btn rl-btn--secondary' onClick={() => setRegenerateConfirm(true)} disabled={busy}>Regenerate recovery codes</button>
              <button type='button' className='rl-btn rl-btn--secondary rl-btn--danger' onClick={onRequestRemove} disabled={busy}>Remove authenticator app</button>
            </div>
          </React.Fragment>}
        </div>}
        {step === 'recovery' &&
        <div className='rl-settings-modal__body'>
          <div className='rl-settings-recovery-grid' aria-label='Recovery codes'>
            {oneTimeCodes.map((code) => <code key={code}>{code}</code>)}
          </div>
          <button type='button' className='rl-btn rl-btn--secondary' onClick={copyAllCodes} disabled={busy || !oneTimeCodes.length}>Copy all codes</button>
          <label className='rl-settings-check-row'>
            <input type='checkbox' checked={savedCodes} onChange={(event) => setSavedCodes(event.target.checked)} />
            <span>I saved my recovery codes</span>
          </label>
          {closeWarning &&
          <div className='rl-settings-warning-box' role='alert'>
            <p>These recovery codes will not be shown again after you close this dialog.</p>
            <div className='rl-settings-modal__actions'>
              <button type='button' className='rl-btn rl-btn--secondary' onClick={() => setCloseWarning(false)}>Return to codes</button>
              <button type='button' className='rl-btn rl-btn--secondary' onClick={finishClose}>Close anyway</button>
            </div>
          </div>}
          {error && <p className='rl-settings-dialog-error' role='alert'>{error}</p>}
          {notice && <p className='rl-settings-dialog-notice' role='status'>{notice}</p>}
          <div className='rl-settings-modal__actions'>
            <button type='button' className='rl-btn rl-btn--secondary' onClick={requestClose} disabled={busy}>Cancel</button>
            <button type='button' className='rl-btn rl-btn--primary' onClick={finishRecoveryStep} disabled={busy || !savedCodes}>Finish</button>
          </div>
        </div>}
      </div>
    </div>);
}

function AccountMfaRemoveDialog({ open, busy, error, onCancel, onConfirm }) {
  const dialogRef = useRef(null);
  const removeButtonRef = useRef(null);
  const previousFocusRef = useRef(null);
  useEffect(() => {
    if (!open) return undefined;
    previousFocusRef.current = document.activeElement;
    const timer = window.setTimeout(() => { if (removeButtonRef.current) removeButtonRef.current.focus(); }, 0);
    return () => {
      window.clearTimeout(timer);
      const previous = previousFocusRef.current;
      if (previous && typeof previous.focus === 'function') previous.focus();
    };
  }, [open]);
  useEffect(() => {
    if (!open) return undefined;
    const handleKeyDown = (event) => { if (event.key === 'Escape' && !busy) onCancel(); };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [open, busy, onCancel]);
  if (!open) return null;
  return (
    <div className='rl-settings-modal-scrim rl-settings-modal-scrim--confirm' onMouseDown={busy ? undefined : onCancel}>
      <div ref={dialogRef} className='rl-settings-modal rl-settings-confirm-modal' role='dialog' aria-modal='true' aria-labelledby='settings-mfa-remove-title' onMouseDown={(event) => event.stopPropagation()} onKeyDown={(event) => trapFocusInDialog(event, dialogRef.current)}>
        <button type='button' className='rl-settings-modal__close' onClick={onCancel} aria-label='Close removal confirmation' disabled={busy}><i data-lucide='x'></i></button>
        <div className='rl-settings-modal__head'>
          <span className='rl-settings-modal__icon rl-settings-modal__icon--warning' aria-hidden='true'><i data-lucide='shield-x'></i></span>
          <h2 id='settings-mfa-remove-title'>Remove authenticator app?</h2>
          <p>You will no longer be asked for an authenticator code when signing in. Make sure you still have another secure way to access your account.</p>
        </div>
        {error && <p className='rl-settings-dialog-error' role='alert'>{error}</p>}
        <div className='rl-settings-modal__actions'>
          <button type='button' className='rl-btn rl-btn--secondary' onClick={onCancel} disabled={busy}>Cancel</button>
          <button ref={removeButtonRef} type='button' className='rl-btn rl-btn--primary rl-btn--danger' onClick={onConfirm} disabled={busy}>{busy ? 'Removing...' : 'Remove authenticator app'}</button>
        </div>
      </div>
    </div>);
}
function AccountPasswordDialog({ open, passwordEnabled, onClose, onSubmit }) {
  const [error, setError] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [signOutOtherSessions, setSignOutOtherSessions] = useState(true);
  const submittingRef = useRef(false);
  const previousFocusRef = useRef(null);
  const currentPasswordRef = useRef(null);
  const newPasswordRef = useRef(null);
  const confirmPasswordRef = useRef(null);
  const setSubmittingState = (value) => {
    submittingRef.current = value;
    setSubmitting(value);
  };
  const clearPasswordFields = () => {
    [currentPasswordRef, newPasswordRef, confirmPasswordRef].forEach((ref) => {
      if (ref.current) ref.current.value = '';
    });
  };
  const closeDialog = () => {
    if (submittingRef.current) return;
    clearPasswordFields();
    setError('');
    setSignOutOtherSessions(true);
    onClose();
  };
  useEffect(() => {
    if (!open) return undefined;
    previousFocusRef.current = document.activeElement;
    setError('');
    setSignOutOtherSessions(true);
    const target = passwordEnabled ? currentPasswordRef : newPasswordRef;
    const timer = window.setTimeout(() => {
      if (target.current) target.current.focus();
    }, 0);
    return () => {
      window.clearTimeout(timer);
      clearPasswordFields();
      const previous = previousFocusRef.current;
      if (previous && typeof previous.focus === 'function') previous.focus();
    };
  }, [open, passwordEnabled]);
  useEffect(() => {
    if (!open) return undefined;
    const handleKeyDown = (event) => {
      if (event.key === 'Escape') closeDialog();
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [open, submitting]);
  if (!open) return null;
  const handleSubmit = (event) => {
    event.preventDefault();
    if (submittingRef.current) return;
    const currentPassword = currentPasswordRef.current ? currentPasswordRef.current.value : '';
    const newPassword = newPasswordRef.current ? newPasswordRef.current.value : '';
    const confirmPassword = confirmPasswordRef.current ? confirmPasswordRef.current.value : '';
    if (passwordEnabled && !currentPassword) { setError('Enter your current password.'); return; }
    if (!newPassword || !confirmPassword) { setError('Enter and confirm your new password.'); return; }
    if (newPassword !== confirmPassword) { setError('New password and confirmation must match.'); return; }
    setSubmittingState(true);
    setError('');
    Promise.resolve(onSubmit({
      currentPassword: passwordEnabled ? currentPassword : undefined,
      newPassword,
      signOutOfOtherSessions: passwordEnabled ? signOutOtherSessions : true,
      hadPassword: passwordEnabled
    })).then(() => {
      clearPasswordFields();
      onClose();
    }).catch((submitError) => {
      clearPasswordFields();
      setError(getSettingsPublicErrorMessage(submitError, 'Your password could not be updated.'));
    }).finally(() => {
      setSubmittingState(false);
    });
  };
  return (
    <div className='rl-settings-modal-scrim' onMouseDown={closeDialog}>
      <div className='rl-settings-modal rl-settings-password-modal' role='dialog' aria-modal='true' aria-labelledby='settings-password-title' onMouseDown={(event) => event.stopPropagation()}>
        <button type='button' className='rl-settings-modal__close' onClick={closeDialog} aria-label='Close password dialog' disabled={submitting}><i data-lucide='x'></i></button>
        <div className='rl-settings-modal__head'>
          <span className='rl-settings-modal__icon' aria-hidden='true'><i data-lucide='key-round'></i></span>
          <h2 id='settings-password-title'>{passwordEnabled ? 'Change password' : 'Add password'}</h2>
          <p>{passwordEnabled ? 'Use a strong password that you do not reuse elsewhere.' : 'Add a password so you can sign in with email and password.'}</p>
        </div>
        <form className='rl-settings-modal__body' onSubmit={handleSubmit}>
          {passwordEnabled &&
          <label className='rl-settings-dialog-field' htmlFor='settings-current-password'>
            <span>Current password</span>
            <input id='settings-current-password' ref={currentPasswordRef} className='rl-input' type='password' autoComplete='current-password' />
          </label>}
          <label className='rl-settings-dialog-field' htmlFor='settings-new-password'>
            <span>New password</span>
            <input id='settings-new-password' ref={newPasswordRef} className='rl-input' type='password' autoComplete='new-password' />
          </label>
          <label className='rl-settings-dialog-field' htmlFor='settings-confirm-password'>
            <span>Confirm new password</span>
            <input id='settings-confirm-password' ref={confirmPasswordRef} className='rl-input' type='password' autoComplete='new-password' />
          </label>
          {passwordEnabled &&
          <label className='rl-settings-check-row'>
            <input type='checkbox' checked={signOutOtherSessions} onChange={(event) => setSignOutOtherSessions(event.target.checked)} />
            <span>Sign out of other devices after changing my password</span>
          </label>}
          {error && <p className='rl-settings-dialog-error' role='alert'>{error}</p>}
          <div className='rl-settings-modal__actions'>
            <button type='button' className='rl-btn rl-btn--secondary' onClick={closeDialog} disabled={submitting}>Cancel</button>
            <button type='submit' className='rl-btn rl-btn--primary' disabled={submitting}>{submitting ? 'Saving...' : passwordEnabled ? 'Change password' : 'Add password'}</button>
          </div>
        </form>
      </div>
    </div>);
}

function AccountSessionsDialog({ open, sessionsState, onClose, onRequestSignOut, onRequestSignOutAll }) {
  const previousFocusRef = useRef(null);
  const closeButtonRef = useRef(null);
  useEffect(() => {
    if (!open) return undefined;
    previousFocusRef.current = document.activeElement;
    const timer = window.setTimeout(() => {
      if (closeButtonRef.current) closeButtonRef.current.focus();
    }, 0);
    return () => {
      window.clearTimeout(timer);
      const previous = previousFocusRef.current;
      if (previous && typeof previous.focus === 'function') previous.focus();
    };
  }, [open]);
  useEffect(() => {
    if (!open) return undefined;
    const handleKeyDown = (event) => {
      if (event.key === 'Escape' && sessionsState.loading !== true) onClose();
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [open, onClose, sessionsState.loading]);
  if (!open) return null;
  const sessions = Array.isArray(sessionsState.sessions) ? sessionsState.sessions : [];
  const otherSessions = sessions.filter((session) => !session.isCurrent);
  const loading = sessionsState.loading === true;
  return (
    <div className='rl-settings-modal-scrim' onMouseDown={loading ? undefined : onClose}>
      <div className='rl-settings-modal rl-settings-sessions-modal' role='dialog' aria-modal='true' aria-labelledby='settings-sessions-title' onMouseDown={(event) => event.stopPropagation()}>
        <button ref={closeButtonRef} type='button' className='rl-settings-modal__close' onClick={onClose} aria-label='Close active sessions' disabled={loading}><i data-lucide='x'></i></button>
        <div className='rl-settings-modal__head'>
          <span className='rl-settings-modal__icon' aria-hidden='true'><i data-lucide='monitor-smartphone'></i></span>
          <h2 id='settings-sessions-title'>Active sessions</h2>
          <p>Review where your ClickLyx account is currently signed in.</p>
        </div>
        {sessionsState.error && <p className='rl-settings-dialog-error' role='alert'>{sessionsState.error}</p>}
        {sessionsState.notice && <p className='rl-settings-dialog-notice' role='status'>{sessionsState.notice}</p>}
        {Array.isArray(sessionsState.failures) && sessionsState.failures.length > 0 &&
        <ul className='rl-settings-session-failures' role='alert'>
          {sessionsState.failures.map((failure) => <li key={failure.sessionId || failure.message}>{failure.message}</li>)}
        </ul>}
        <div className='rl-settings-session-list'>
          {loading && !sessions.length ? <p className='rl-settings-empty'>Loading sessions...</p> : null}
          {!loading && !sessions.length && !sessionsState.error ? <p className='rl-settings-empty'>No active sessions found.</p> : null}
          {sessions.map((session) =>
          <div className='rl-settings-session-item' key={session.id || session.lastActiveAt}>
            <div className='rl-settings-session-item__main'>
              <div className='rl-settings-session-title'>
                <strong>{session.device || 'Unknown device'}</strong>
                {session.isCurrent && <span className='rl-settings-session-badge'>This device</span>}
              </div>
              <dl className='rl-settings-session-meta'>
                <div><dt>Browser</dt><dd>{session.browser || 'Browser unavailable'}</dd></div>
                <div><dt>Location</dt><dd>{session.location || 'Location unavailable'}</dd></div>
                <div><dt>Last active</dt><dd>{session.lastActiveAt || 'Last active unavailable'}</dd></div>
              </dl>
            </div>
            {!session.isCurrent && <button type='button' className='rl-btn rl-btn--secondary' onClick={() => onRequestSignOut(session)} disabled={loading}>Sign out</button>}
          </div>)}
        </div>
        <div className='rl-settings-modal__actions'>
          <button type='button' className='rl-btn rl-btn--secondary' onClick={onClose} disabled={loading}>Done</button>
          <button type='button' className='rl-btn rl-btn--primary' onClick={onRequestSignOutAll} disabled={loading || otherSessions.length === 0}>Sign out all other sessions</button>
        </div>
      </div>
    </div>);
}

function AccountSessionConfirmDialog({ request, busy, onCancel, onConfirm }) {
  const confirmButtonRef = useRef(null);
  useEffect(() => {
    if (!request) return undefined;
    const timer = window.setTimeout(() => {
      if (confirmButtonRef.current) confirmButtonRef.current.focus();
    }, 0);
    const handleKeyDown = (event) => {
      if (event.key === 'Escape' && !busy) onCancel();
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => {
      window.clearTimeout(timer);
      window.removeEventListener('keydown', handleKeyDown);
    };
  }, [request, busy]);
  if (!request) return null;
  const allOther = request.mode === 'all';
  return (
    <div className='rl-settings-modal-scrim rl-settings-modal-scrim--confirm' onMouseDown={busy ? undefined : onCancel}>
      <div className='rl-settings-modal rl-settings-confirm-modal' role='dialog' aria-modal='true' aria-labelledby='settings-session-confirm-title' onMouseDown={(event) => event.stopPropagation()}>
        <button type='button' className='rl-settings-modal__close' onClick={onCancel} aria-label='Close confirmation' disabled={busy}><i data-lucide='x'></i></button>
        <div className='rl-settings-modal__head'>
          <span className='rl-settings-modal__icon rl-settings-modal__icon--warning' aria-hidden='true'><i data-lucide='log-out'></i></span>
          <h2 id='settings-session-confirm-title'>{allOther ? 'Sign out all other sessions?' : 'Sign out this session?'}</h2>
          <p>{allOther ? 'Your current device will stay signed in. Other devices may need to sign in again.' : 'That device will need to sign in again before using ClickLyx.'}</p>
        </div>
        <div className='rl-settings-modal__actions'>
          <button type='button' className='rl-btn rl-btn--secondary' onClick={onCancel} disabled={busy}>Cancel</button>
          <button ref={confirmButtonRef} type='button' className='rl-btn rl-btn--primary' onClick={onConfirm} disabled={busy}>{busy ? 'Signing out...' : 'Sign out'}</button>
        </div>
      </div>
    </div>);
}
function WorkspaceInviteMemberDialog({ open, form, emailInputRef, onEmailChange, onRoleChange, onCancel, onSubmit, growthDisabled = false }) {
  const dialogRef = useRef(null);
  const closeButtonRef = useRef(null);
  const submitting = form && form.submitting === true;
  useEffect(() => {
    if (!open) return undefined;
    const timer = window.setTimeout(() => {
      if (emailInputRef && emailInputRef.current) emailInputRef.current.focus();
      else if (closeButtonRef.current) closeButtonRef.current.focus();
    }, 0);
    const handleKeyDown = (event) => {
      if (event.key === 'Escape' && !submitting) onCancel();
    };
    document.addEventListener('keydown', handleKeyDown);
    return () => {
      window.clearTimeout(timer);
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [open, submitting, onCancel]);
  if (!open) return null;
  const roleDescription = getWorkspaceInvitationRoleDescription(form.role);
  return (
    <div className='rl-settings-modal-scrim' onMouseDown={submitting ? undefined : onCancel}>
      <div ref={dialogRef} className='rl-settings-modal rl-settings-workspace-invite-modal' role='dialog' aria-modal='true' aria-labelledby='settings-workspace-invite-title' onMouseDown={(event) => event.stopPropagation()} onKeyDown={(event) => trapFocusInDialog(event, dialogRef.current)}>
        <button ref={closeButtonRef} type='button' className='rl-settings-modal__close' onClick={onCancel} aria-label='Close invite member' disabled={submitting}><i data-lucide='x'></i></button>
        <div className='rl-settings-modal__head'>
          <span className='rl-settings-modal__icon' aria-hidden='true'><i data-lucide='user-plus'></i></span>
          <h2 id='settings-workspace-invite-title'>Invite member</h2>
          <p>Invite someone to join this workspace.</p>
        </div>
        <form className='rl-settings-modal__body' onSubmit={onSubmit}>
          <label className='rl-settings-dialog-field' htmlFor='settings-workspace-invite-email'>
            <span>Email address</span>
            <input id='settings-workspace-invite-email' ref={emailInputRef} className='rl-input' type='email' inputMode='email' autoComplete='email' value={form.emailAddress} onChange={(event) => !growthDisabled && onEmailChange(event.target.value)} disabled={submitting || growthDisabled} aria-invalid={form.emailError ? 'true' : undefined} aria-describedby={form.emailError ? 'settings-workspace-invite-email-error' : undefined} />
          </label>
          {form.emailError && <p id='settings-workspace-invite-email-error' className='rl-settings-dialog-error' role='alert'>{form.emailError}</p>}
          <label className='rl-settings-dialog-field' htmlFor='settings-workspace-invite-role'>
            <span>Role</span>
            <select id='settings-workspace-invite-role' className='rl-input' value={form.role} onChange={(event) => !growthDisabled && onRoleChange(event.target.value)} disabled={submitting || growthDisabled}>
              {WORKSPACE_INVITATION_ROLE_OPTIONS.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
            </select>
          </label>
          <p className='rl-settings-role-helper'>{roleDescription}</p>
          {form.error && <p className='rl-settings-dialog-error' role='alert'>{form.error}</p>}
          <div className='rl-settings-modal__actions'>
            <button type='button' className='rl-btn rl-btn--secondary' onClick={onCancel} disabled={submitting}>Cancel</button>
            <button type='submit' className='rl-btn rl-btn--primary' disabled={submitting || growthDisabled}>{submitting ? 'Sending...' : 'Send invitation'}</button>
          </div>
        </form>
      </div>
    </div>);
}

function WorkspaceInvitationCancelDialog({ invitation, busy, error, onCancel, onConfirm }) {
  const confirmButtonRef = useRef(null);
  const dialogRef = useRef(null);
  useEffect(() => {
    if (!invitation) return undefined;
    const timer = window.setTimeout(() => {
      if (confirmButtonRef.current) confirmButtonRef.current.focus();
    }, 0);
    const handleKeyDown = (event) => {
      if (event.key === 'Escape' && !busy) onCancel();
    };
    document.addEventListener('keydown', handleKeyDown);
    return () => {
      window.clearTimeout(timer);
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, [invitation, busy, onCancel]);
  if (!invitation) return null;
  const emailAddress = invitation.emailAddress || 'this invitee';
  return (
    <div className='rl-settings-modal-scrim rl-settings-modal-scrim--confirm' onMouseDown={busy ? undefined : onCancel}>
      <div ref={dialogRef} className='rl-settings-modal rl-settings-confirm-modal' role='dialog' aria-modal='true' aria-labelledby='settings-workspace-cancel-invitation-title' onMouseDown={(event) => event.stopPropagation()} onKeyDown={(event) => trapFocusInDialog(event, dialogRef.current)}>
        <button type='button' className='rl-settings-modal__close' onClick={onCancel} aria-label='Close invitation cancellation' disabled={busy}><i data-lucide='x'></i></button>
        <div className='rl-settings-modal__head'>
          <span className='rl-settings-modal__icon rl-settings-modal__icon--warning' aria-hidden='true'><i data-lucide='user-x'></i></span>
          <h2 id='settings-workspace-cancel-invitation-title'>Cancel invitation?</h2>
          <p>The invitation for {emailAddress} will no longer be usable.</p>
        </div>
        {error && <p className='rl-settings-dialog-error' role='alert'>{error}</p>}
        <div className='rl-settings-modal__actions'>
          <button type='button' className='rl-btn rl-btn--secondary' onClick={onCancel} disabled={busy}>Keep invitation</button>
          <button ref={confirmButtonRef} type='button' className='rl-btn rl-btn--primary rl-btn--danger' onClick={onConfirm} disabled={busy}>{busy ? 'Canceling...' : 'Cancel invitation'}</button>
        </div>
      </div>
    </div>);
}

function WorkspaceRemoveMemberDialog({ member, busy, error, onCancel, onConfirm }) {
  const dialogRef = useRef(null);
  const confirmButtonRef = useRef(null);
  useEffect(() => {
    if (!member) return;
    window.setTimeout(() => confirmButtonRef.current && confirmButtonRef.current.focus(), 0);
  }, [member]);
  if (!member) return null;
  const memberName = member.displayName || member.emailAddress || 'this member';
  return (
    <div className='rl-settings-modal-scrim rl-settings-modal-scrim--confirm' onMouseDown={busy ? undefined : onCancel}>
      <div ref={dialogRef} className='rl-settings-modal rl-settings-confirm-modal' role='dialog' aria-modal='true' aria-labelledby='settings-workspace-remove-member-title' onMouseDown={(event) => event.stopPropagation()} onKeyDown={(event) => trapFocusInDialog(event, dialogRef.current)}>
        <button type='button' className='rl-settings-modal__close' onClick={onCancel} aria-label='Close member removal' disabled={busy}><i data-lucide='x'></i></button>
        <div className='rl-settings-modal__head'>
          <span className='rl-settings-modal__icon rl-settings-modal__icon--warning' aria-hidden='true'><i data-lucide='user-minus'></i></span>
          <h2 id='settings-workspace-remove-member-title'>Remove member?</h2>
          <p>{memberName} will immediately lose access to this Workspace. This action removes their access only and does not delete the Workspace.</p>
        </div>
        {error && <p className='rl-settings-dialog-error' role='alert'>{error}</p>}
        <div className='rl-settings-modal__actions'>
          <button type='button' className='rl-btn rl-btn--secondary' onClick={onCancel} disabled={busy}>Keep member</button>
          <button ref={confirmButtonRef} type='button' className='rl-btn rl-btn--primary rl-btn--danger' onClick={onConfirm} disabled={busy}>{busy ? 'Removing...' : 'Remove member'}</button>
        </div>
      </div>
    </div>);
}

const CANCELLATION_REASON_OPTIONS = Object.freeze([
  { value: 'too_expensive', label: 'It’s too expensive' },
  { value: 'missing_features', label: 'It’s missing features I need' },
  { value: 'switched_service', label: 'I switched to another service' },
  { value: 'unused', label: 'I’m not using it enough' },
  { value: 'low_quality', label: 'The output quality isn’t right for me' },
  { value: 'too_complex', label: 'It’s too complex' },
  { value: 'customer_service', label: 'I had a customer service issue' },
  { value: 'other', label: 'Other' }
]);

const RANK_LYX_TESTIMONIAL = 'As the Chief Editor at Rank Lyx, I\'ve used many AI writing tools that promised to write content in my tone or our clients\' tone. But again and again, I was disappointed by the typical AI wording, the overuse of em dashes, and the huge amount of editing required. Clicklyx removed that frustration from day one, and I\'ve never looked back. Top-quality content that sounds human, that sounds like me.';

function SubscriptionCancellationDialog({
  flow, busy, error, onClose, onBack, onContinue, onReasonChange, onCommentChange,
  onReasonContinue, onAcceptRetention, onDeclineSecondChance, onConfirmCancellation,
  onConfirmReverse
}) {
  const dialogRef = useRef(null);
  const closeButtonRef = useRef(null);
  const contentRef = useRef(null);
  const onCloseRef = useRef(onClose);
  onCloseRef.current = onClose;
  const step = flow && flow.step;
  const lockedResult = ['cancel_success', 'reversing', 'reverse_success'].includes(step);
  React.useLayoutEffect(() => {
    if (!lockedResult || !dialogRef.current || !contentRef.current) {
      if (dialogRef.current) dialogRef.current.style.height = '';
      return undefined;
    }
    const dialog = dialogRef.current;
    const content = contentRef.current;
    const resize = () => {
      const style = window.getComputedStyle(dialog);
      const chrome = ['paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth']
        .reduce((sum, key) => sum + (parseFloat(style[key]) || 0), 0);
      dialog.style.height = Math.ceil(content.getBoundingClientRect().height + chrome) + 'px';
    };
    resize();
    const observer = typeof window.ResizeObserver === 'function' ? new window.ResizeObserver(resize) : null;
    if (observer) observer.observe(content);
    window.addEventListener('resize', resize);
    return () => {
      if (observer) observer.disconnect();
      window.removeEventListener('resize', resize);
    };
  }, [step, lockedResult]);
  useEffect(() => {
    if (!flow) return undefined;
    const dialog = dialogRef.current;
    const initial = lockedResult ? dialog.querySelector('[data-cancellation-done]') || dialog : closeButtonRef.current;
    if (initial) initial.focus();
    const handleKeyDown = (event) => {
      if (event.key !== 'Escape') return;
      if (lockedResult || busy) event.preventDefault();
      else onCloseRef.current();
    };
    const containFocus = (event) => {
      if (dialog && !dialog.contains(event.target)) (initial || dialog).focus();
    };
    document.addEventListener('keydown', handleKeyDown);
    document.addEventListener('focusin', containFocus);
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
      document.removeEventListener('focusin', containFocus);
    };
  }, [step, busy, lockedResult]);
  if (!flow) return null;
  const eligible = flow.retentionStatus === 'eligible';
  const support = <a className='rl-cancellation-support' href='https://clicklyx.com/contact-support/' target='_blank' rel='noopener noreferrer'>Contact support</a>;
  const offer = <div className='rl-cancellation-offer'>
    <span className='rl-cancellation-offer__eyebrow'>A thank-you for staying</span>
    <strong>20% off</strong>
    <p>Save 20% on your next 3 monthly renewals.</p>
  </div>;
  const actions = (secondary, primary) => <div className='rl-settings-modal__actions'>{secondary}{primary}</div>;
  return (
    <div className='rl-settings-modal-scrim rl-settings-modal-scrim--confirm' onMouseDown={busy || lockedResult ? undefined : onClose}>
      <div ref={dialogRef} className='rl-settings-modal rl-cancellation-modal' role='dialog' aria-modal='true' aria-labelledby='settings-subscription-cancellation-title' aria-describedby={lockedResult ? 'settings-subscription-cancellation-body' : undefined} aria-busy={step === 'reversing' ? true : undefined} tabIndex={-1} data-cancellation-step={step} onMouseDown={(event) => event.stopPropagation()} onKeyDown={(event) => {
        if (event.key === 'Tab' && !dialogRef.current.querySelector('button, [href], input, select, textarea')) {
          event.preventDefault();
          dialogRef.current.focus();
        } else trapFocusInDialog(event, dialogRef.current);
      }}>
        <div ref={contentRef} className='rl-cancellation-content'>
        {!lockedResult && <button ref={closeButtonRef} type='button' className='rl-settings-modal__close' onClick={onClose} aria-label='Close cancellation flow' disabled={busy}><i data-lucide='x'></i></button>}
        {step === 'step1' && <>
          <div className='rl-settings-modal__head rl-cancellation-step1-head'>
            <h2 id='settings-subscription-cancellation-title'>Before you cancel</h2>
          </div>
          <div className='rl-cancellation-intro'>
            <section aria-labelledby='cancellation-loss-heading'>
              <h3 id='cancellation-loss-heading'>Before you go, here’s what happens next</h3>
              <p className='rl-cancellation-loss-intro'>Your Workspace stays fully active through <strong>{flow.periodEndLabel}</strong>. After that, you’ll no longer be able to:</p>
              <ul className='rl-cancellation-loss-list'>
                {['Write SEO-optimized articles', 'Create content with extensive research', 'Use your brand and product knowledge'].map((item) => <li key={item}><i data-lucide='x'></i><span>{item}</span></li>)}
              </ul>
            </section>
            <section aria-label={eligible ? 'Retention offer' : 'Customer testimonial'}>
              {eligible ? offer : <figure className='rl-cancellation-testimonial'>
                <blockquote>“{RANK_LYX_TESTIMONIAL}”</blockquote>
                <figcaption>
                  <img src='assets/rank-lyx-logo.png' alt='Rank Lyx' />
                  <span><strong>Yoofi Biney</strong><small>Chief Editor, Rank Lyx</small></span>
                </figcaption>
              </figure>}
            </section>
          </div>
          {actions(
            eligible && <button type='button' className='rl-btn rl-btn--secondary' onClick={onContinue}>Continue cancellation</button>,
            <button type='button' className='rl-btn rl-btn--primary' onClick={eligible ? onAcceptRetention : onContinue}>{eligible ? 'Accept 20% offer' : 'Continue cancellation'}</button>
          )}
        </>}
        {step === 'reason' && <>
          <div className='rl-settings-modal__head'>
            <h2 id='settings-subscription-cancellation-title'>What didn’t work out with Clicklyx?</h2>
            <p>We’re sorry to see you go. What could we have done better?</p>
          </div>
          <fieldset className='rl-cancellation-reasons' aria-label='Cancellation reason'>
            {CANCELLATION_REASON_OPTIONS.map((option) => <label key={option.value}>
              <input type='radio' name='cancellation-reason' value={option.value} checked={flow.reason === option.value} onChange={() => onReasonChange(option.value)} />
              <span>{option.label}</span>
            </label>)}
          </fieldset>
          <label className='rl-settings-dialog-field rl-cancellation-comment'>
            <span>{flow.reason === 'other' ? 'Tell us more (required)' : 'Anything else? (optional)'}</span>
            <textarea value={flow.comment} onChange={(event) => onCommentChange(event.target.value)} rows='4' aria-describedby='cancellation-comment-help'></textarea>
            <small id='cancellation-comment-help'>{Array.from(flow.comment || '').length} / 500 characters</small>
          </label>
          {flow.validation && <p className='rl-settings-dialog-error' role='alert'>{flow.validation}</p>}
          {actions(
            <button type='button' className='rl-btn rl-btn--secondary' onClick={onBack}>Back</button>,
            <button type='button' className='rl-btn rl-btn--primary' onClick={onReasonContinue}>Continue</button>
          )}
        </>}
        {step === 'second_chance' && <>
          <div className='rl-settings-modal__head'>
            <span className='rl-settings-modal__icon' aria-hidden='true'><i data-lucide='gift'></i></span>
            <h2 id='settings-subscription-cancellation-title'>Would 20% off help?</h2>
            <p>You can keep your Workspace active and use the same plan.</p>
          </div>
          {offer}
          {actions(
            <button type='button' className='rl-btn rl-btn--secondary' onClick={onDeclineSecondChance}>No thanks, continue</button>,
            <button type='button' className='rl-btn rl-btn--primary' onClick={onAcceptRetention}>Accept 20% offer</button>
          )}
        </>}
        {step === 'final_confirm' && <>
          <div className='rl-settings-modal__head rl-cancellation-final-head'>
            <h2 id='settings-subscription-cancellation-title'>We’re still here for you</h2>
            <p>Your Workspace stays fully active through <strong>{flow.periodEndLabel}</strong>. After that, your Workspace moves to read-only access, so you can still view your existing content.</p>
          </div>
          <section className='rl-cancellation-live-support' aria-labelledby='cancellation-live-support-title'>
            <h3 id='cancellation-live-support-title'>Chat with live support</h3>
            <p>Still unsure? Our team is here to help with any questions before you leave.</p>
            <a className='rl-btn rl-btn--secondary rl-cancellation-chat-button' href='https://clicklyx.com/contact-support/' target='_blank' rel='noopener noreferrer'>Chat now</a>
          </section>
          {actions(
            <button type='button' className='rl-btn rl-btn--secondary' onClick={onClose}>Don’t cancel</button>,
            <button type='button' className='rl-btn rl-btn--primary rl-btn--danger' onClick={onConfirmCancellation}>Cancel my plan</button>
          )}
        </>}
        {step === 'reverse_confirm' && <>
          <div className='rl-settings-modal__head'>
            <span className='rl-settings-modal__icon' aria-hidden='true'><i data-lucide='calendar-check'></i></span>
            <h2 id='settings-subscription-cancellation-title'>Keep your subscription?</h2>
            <p>The scheduled cancellation will be removed. Your current subscription will continue and renew on {flow.periodEndLabel}. This does not create a new subscription or change the current billing period.</p>
          </div>
          {actions(
            <button type='button' className='rl-btn rl-btn--secondary' onClick={onClose}>Go back</button>,
            <button type='button' className='rl-btn rl-btn--primary' onClick={onConfirmReverse}>Keep subscription</button>
          )}
        </>}
        {(step === 'applying_retention' || step === 'scheduling_cancel') && <div className='rl-cancellation-result' role='status'>
          <span className='rl-cancellation-spinner' aria-hidden='true'></span>
          <h2 id='settings-subscription-cancellation-title'>{step === 'applying_retention' ? 'Applying your offer' : step === 'scheduling_cancel' ? 'Scheduling cancellation' : 'Keeping your subscription'}</h2>
          <p>Please keep this window open.</p>
        </div>}
        {step === 'reversing' && <div className='rl-cancellation-result rl-cancellation-result--continuous'>
          <div className='rl-cancellation-progress-title'>
            <span className='rl-cancellation-spinner' aria-hidden='true'></span>
            <h2 id='settings-subscription-cancellation-title'>Keeping your subscription</h2>
          </div>
          <p id='settings-subscription-cancellation-body'>Do not press the back button. Please keep this tab open while we confirm that your subscription will continue.</p>
          <span className='rl-cancellation-sr-status' role='status' aria-live='polite'>Keeping your subscription</span>
        </div>}
        {(step === 'cancel_sync_pending' || step === 'reverse_sync_pending') && <div className='rl-cancellation-result' role='status'>
          <h2 id='settings-subscription-cancellation-title'>{step === 'cancel_sync_pending' ? 'Cancellation scheduled' : 'Keeping your subscription'}</h2>
          <p>{step === 'cancel_sync_pending' ? window.RankLyxWorkspaceCommercial.CANCELLATION_SYNC_PENDING_MESSAGE : window.RankLyxWorkspaceCommercial.REVERSAL_SYNC_PENDING_MESSAGE}</p>
        </div>}
        {step === 'retention_success' && <div className='rl-cancellation-result' role='status'>
          <span className='rl-settings-modal__icon rl-cancellation-result__success' aria-hidden='true'><i data-lucide='circle-check'></i></span>
          <h2 id='settings-subscription-cancellation-title'>You’re staying with Clicklyx</h2>
          <p>Your 20% offer for the next 3 monthly renewals was applied. Your Workspace remains active.</p>
          {actions(null, <button type='button' className='rl-btn rl-btn--primary' onClick={onClose}>Done</button>)}
        </div>}
        {step === 'cancel_success' && <div className='rl-cancellation-result' role='status'>
          <h2 id='settings-subscription-cancellation-title'>You've canceled your subscription</h2>
          <p id='settings-subscription-cancellation-body'>You can continue using Clicklyx through {flow.periodEndLabel}. After that, you'll still be able to access your existing content.</p>
          {actions(
            <button type='button' className='rl-cancellation-done' data-cancellation-done onClick={onClose}>Done</button>,
            <button type='button' className='rl-btn rl-btn--primary' onClick={onConfirmReverse}>Keep my subscription</button>
          )}
        </div>}
        {step === 'reverse_success' && <div className='rl-cancellation-result' role='status'>
          <h2 id='settings-subscription-cancellation-title'>Your subscription will continue</h2>
          <p id='settings-subscription-cancellation-body'>Your subscription will continue as usual, and your next renewal is scheduled for {flow.periodEndLabel}.</p>
          {actions(null, <button type='button' className='rl-btn rl-btn--primary' data-cancellation-done onClick={onClose}>Done</button>)}
        </div>}
        {step === 'retention_error' && <div className='rl-cancellation-result'>
          <span className='rl-settings-modal__icon rl-settings-modal__icon--warning' aria-hidden='true'><i data-lucide='circle-alert'></i></span>
          <h2 id='settings-subscription-cancellation-title'>We couldn’t apply the offer</h2>
          <p role='alert'>{error || 'The offer could not be applied. Please try again.'}</p>
          {actions(
            <button type='button' className='rl-btn rl-btn--secondary' onClick={flow.retentionSource === 'second' ? onDeclineSecondChance : onContinue}>Continue cancellation</button>,
            <button type='button' className='rl-btn rl-btn--primary' onClick={onAcceptRetention}>Try offer again</button>
          )}
        </div>}
        {error && step !== 'retention_error' && <p className='rl-settings-dialog-error' role='alert'>{error}</p>}
        {!lockedResult && <div className='rl-cancellation-help'>{support}</div>}
        </div>
      </div>
    </div>);
}

const TALK_TO_SALES_URL = 'https://clicklyx.com/contact-sales/';
const LEGACY_CHECKOUT_FEATURE_CATEGORY_BY_LABEL = Object.freeze({
  'Brand Profile': 'Knowledge', 'Product Knowledge': 'Knowledge', 'Brand Voice': 'Knowledge',
  'ICP profiles': 'Knowledge', 'AI-assisted ICP creation': 'Knowledge',
  'Brief creation': 'Creation & AI', 'Outline Agent': 'Creation & AI',
  'AI Research Agent': 'Creation & AI', 'Writing Agent': 'Creation & AI',
  'Article Editor': 'Creation & AI', 'AI Chat': 'Creation & AI',
  'Editorial Content Calendar': 'Planning & Management', 'Article library': 'Planning & Management'
});
const LEGACY_CHECKOUT_FEATURE_CATEGORY_ORDER = Object.freeze([
  'Knowledge', 'Creation & AI', 'Planning & Management', 'More features'
]);

function createCheckoutComparisonGroups(catalog, presentations, activeRedesign) {
  const values = (value) => catalog.plans.map(value);
  if (!activeRedesign) {
    const capacityRows = [
      { label: 'Articles', value: (plan) => presentations[plan.planKey] && presentations[plan.planKey].articles },
      { label: 'Users', value: (plan) => presentations[plan.planKey] && presentations[plan.planKey].users },
      { label: 'Websites', value: (plan) => presentations[plan.planKey] && presentations[plan.planKey].websites },
      { label: 'ICP profiles per website', value: (plan) => 'Up to ' + String(plan.icpProfilesPerWebsite) }
    ].map((row) => ({ label: row.label, values: values(row.value) }));
    const categorized = {};
    LEGACY_CHECKOUT_FEATURE_CATEGORY_ORDER.forEach((category) => { categorized[category] = []; });
    catalog.coreFeatures.forEach((feature) => {
      const category = LEGACY_CHECKOUT_FEATURE_CATEGORY_BY_LABEL[feature] || 'More features';
      categorized[category].push({ label: feature, values: values(() => true) });
    });
    const groups = [{ title: 'Usage & Capacity', rows: capacityRows }];
    LEGACY_CHECKOUT_FEATURE_CATEGORY_ORDER.forEach((title) => {
      if (categorized[title].length) groups.push({ title, rows: categorized[title] });
    });
    groups.push({ title: 'Team Collaboration', rows: catalog.collaborationFeatures.map((feature) => ({
      label: feature, values: values((plan) => plan.collaborationEnabled)
    })) });
    return groups;
  }
  const all = values(() => true);
  const knowledgeLimit = (plan, starterValue, teamValue) => plan.planKey === 'starter' ? starterValue : teamValue;
  return [
    { title: 'Usage & Capacity', rows: [
      { label: 'Articles', values: values((plan) => presentations[plan.planKey] && presentations[plan.planKey].articles) },
      { label: 'Users', values: values((plan) => presentations[plan.planKey] && presentations[plan.planKey].users) },
      { label: 'Websites', values: values((plan) => presentations[plan.planKey] && presentations[plan.planKey].websites) },
      { label: 'AI Chat (Coming soon)', values: values(() => false) }
    ] },
    { title: 'Knowledge', rows: [
      { label: 'Brand Profile', values: values(() => '1/website') },
      { label: 'Product Knowledge', values: values(() => '1/website') },
      { label: 'Brand Voice', values: values((plan) => knowledgeLimit(plan, 'Up to 3', 'Up to 3/website')) },
      { label: 'ICP profiles', values: values((plan) => knowledgeLimit(plan, 'Up to 3', 'Up to 3/website')) },
      { label: 'AI knowledge assistant', values: all }
    ] },
    { title: 'Creation & AI', rows: [
      { label: 'Outline Agent', values: all },
      { label: 'AI Research Agent', values: all },
      { label: 'Writing Agent', values: all },
      { label: 'AI Article Editor', values: all }
    ] },
    { title: 'Planning & Management', rows: [
      { label: 'Editorial Content Calendar', values: all },
      { label: 'Article library', values: all }
    ] },
    { title: 'Team Collaboration', rows: [
      'Invite teammates', 'Shared Workspace', 'Shared articles', 'Shared Knowledge',
      'Shared Content Calendar', 'Administrator & Member roles'
    ].map((label) => ({ label, values: values((plan) => plan.collaborationEnabled) })) }
  ];
}

function CheckoutComparisonValue({ value, activeRedesign }) {
  if (typeof value !== 'boolean') return <span>{value}</span>;
  return value
    ? <span className="rl-checkout-comparison__included" aria-label="Included"><i data-lucide="check" aria-hidden="true"></i></span>
    : <span className="rl-checkout-comparison__excluded" aria-label="Not included">{activeRedesign ? '—' : <i data-lucide="minus" aria-hidden="true"></i>}</span>;
}

const ACTIVE_BILLING_CARD_DESCRIPTIONS = Object.freeze({
  starter: 'Ideal for individuals and small businesses',
  growth: 'Ideal for fast growing teams and businesses',
  scale: 'Ideal for agencies and large editorial websites'
});

function getActiveBillingCardFeatures(plan, presentation) {
  const perWebsite = plan.planKey === 'growth' || plan.planKey === 'scale' ? '/website' : '';
  return [
    presentation.articles,
    presentation.users,
    presentation.websites,
    '1 brand profile' + perWebsite,
    '1 product knowledge' + perWebsite,
    'Up to 3 brand voices' + perWebsite,
    'Up to ' + plan.icpProfilesPerWebsite + ' ICP profiles' + perWebsite
  ];
}

function BillingLifecycleNotice({ kind, periodEndDate, onStopCancellation, onUpgrade, disabled }) {
  const scheduled = kind === 'scheduled-cancellation';
  useLucide([kind]);
  return <div className="rl-billing-active__lifecycle-notice" data-billing-lifecycle-notice={kind}>
    <span className="rl-billing-active__lifecycle-icon" aria-hidden="true"><i data-lucide="arrow-up"></i></span>
    <div className="rl-billing-active__lifecycle-copy">
      <h3>{scheduled ? 'Keep your subscription' : 'Upgrade your plan'}</h3>
      <p>{scheduled
        ? `Your subscription is scheduled to end on ${periodEndDate}. You'll continue to have full access until then.`
        : 'Upgrade to start creating new articles and using Clicklyx features again.'}</p>
    </div>
    <button type="button" className="rl-billing-active__lifecycle-action"
      onClick={scheduled ? onStopCancellation : onUpgrade} disabled={disabled}>
      {scheduled ? 'Stop cancellation' : 'Upgrade'}
    </button>
  </div>;
}

function CheckoutPlanSelector({
  catalog, heading, billingInterval, checkoutState, currentPlanKey, currentBillingInterval,
  hasCurrentSubscription, upgradeProjection, upgradeFlow, onBillingIntervalChange,
  onChoosePlan, onChooseUpgrade, activeRedesign, freeRedesign
}) {
  const runtime = getWorkspaceCommercialRuntime();
  const [featuresExpanded, setFeaturesExpanded] = useState(() => !!activeRedesign);
  const busy = ['creating', 'redirecting', 'current_subscription', 'completion_pending'].includes(checkoutState.status);
  const upgradeBusy = !!(upgradeFlow && ['submitting', 'authenticating', 'confirming'].includes(upgradeFlow.status));
  const tierRanks = { starter: 1, growth: 2, scale: 3 };
  const sourcePlanKey = upgradeProjection && upgradeProjection.currentPlanKey || currentPlanKey;
  const presentations = {};
  catalog.plans.forEach((plan) => {
    presentations[plan.planKey] = runtime && typeof runtime.getCheckoutPlanPresentation === 'function'
      ? runtime.getCheckoutPlanPresentation(catalog, plan, billingInterval)
      : null;
  });
  const comparisonGroups = createCheckoutComparisonGroups(catalog, presentations, activeRedesign);
  useLucide([billingInterval, checkoutState.status, currentPlanKey, featuresExpanded, upgradeFlow && upgradeFlow.status]);
  return (
    <section className={'rl-checkout-plans' + (activeRedesign ? ' rl-checkout-plans--billing-active' : '')} aria-labelledby="settings-checkout-plans-title" data-checkout-catalog={catalog.catalogKey}>
      <div className="rl-checkout-plans__head">
        <div>
          <h2 id="settings-checkout-plans-title" tabIndex={freeRedesign ? -1 : undefined}>{heading}</h2>
          <p>{activeRedesign ? 'Publishing high-quality content creates more business opportunities. Learn more about upgrades.' : 'Select the plan and billing cadence that fit this Workspace.'}</p>
        </div>
        <div className="rl-checkout-cadence" role="group" aria-label="Billing cadence">
          {['monthly', 'annual'].map((interval) =>
            <button
              type="button"
              key={interval}
              className={billingInterval === interval ? 'rl-checkout-cadence__option rl-checkout-cadence__option--active' : 'rl-checkout-cadence__option'}
              aria-pressed={billingInterval === interval}
              disabled={busy}
              onClick={() => onBillingIntervalChange(interval)}>
              {interval === 'monthly' ? 'Monthly' : 'Annual'}
            </button>
          )}
        </div>
      </div>
      <div className="rl-checkout-plan-grid">
        {catalog.plans.map((plan) => {
          const presentation = presentations[plan.planKey];
          const recurringAmount = plan[billingInterval] && plan[billingInterval].amount;
          const activePrice = activeRedesign && runtime && typeof runtime.formatCheckoutMoney === 'function'
            ? runtime.formatCheckoutMoney(recurringAmount, catalog.currency) : '';
          const selectedAttempt = checkoutState.planKey === plan.planKey && checkoutState.billingInterval === billingInterval;
          const retryWithNewKey = selectedAttempt && checkoutState.status === 'terminal';
          const isCurrentPlan = hasCurrentSubscription && currentPlanKey === plan.planKey
            && currentBillingInterval === billingInterval;
          const planChangeUnavailable = hasCurrentSubscription && !isCurrentPlan;
          const sameCadenceUpgrade = planChangeUnavailable && upgradeProjection
            && upgradeProjection.billingInterval === billingInterval;
          const higherTier = sameCadenceUpgrade
            && tierRanks[plan.planKey] > tierRanks[sourcePlanKey];
          const upgradeAvailable = higherTier && upgradeProjection.eligible === true;
          let unavailableCopy = 'Plan changes coming soon';
          if (higherTier && upgradeProjection.reason === 'keep_subscription_first') unavailableCopy = 'Keep subscription to upgrade';
          else if (higherTier && upgradeProjection.reason === 'billing_recovery_required') unavailableCopy = 'Manage billing to upgrade';
          else if (planChangeUnavailable && upgradeProjection
            && upgradeProjection.billingInterval !== billingInterval
            && tierRanks[plan.planKey] > tierRanks[sourcePlanKey]) unavailableCopy = 'Cadence changes coming soon';
          return <article className={'rl-checkout-plan' + (plan.recommended ? ' rl-checkout-plan--recommended' : '')} key={plan.planKey} aria-labelledby={'checkout-plan-' + plan.planKey}>
            <div className="rl-checkout-plan__head">
              <h3 id={'checkout-plan-' + plan.planKey}>{plan.name}</h3>
              {plan.recommended && <span className="rl-checkout-plan__badge">{activeRedesign ? 'Most popular' : 'Most Popular'}</span>}
            </div>
            <p className="rl-checkout-plan__best-for">{activeRedesign ? ACTIVE_BILLING_CARD_DESCRIPTIONS[plan.planKey] : plan.bestFor}</p>
            {presentation && <div className="rl-checkout-plan__pricing">
              <div className="rl-checkout-plan__price">
                <strong>{activePrice || presentation.price}</strong>
                <span>{activeRedesign ? '/' : '/ '}{activeRedesign && billingInterval === 'annual' ? 'year' : 'month'}</span>
                {presentation.savings && <span className="rl-checkout-plan__savings">{presentation.savings}</span>}
              </div>
            </div>}
            <div className="rl-checkout-plan__action-stack">
              <div className="rl-checkout-plan__action">
                {isCurrentPlan
                  // Replace this subtree as a unit: Lucide replaces its icon DOM node.
                  ? <React.Fragment key="current-plan">
                      <button type="button" className="rl-btn rl-checkout-plan__cta rl-checkout-plan__polish-action rl-checkout-plan__cta--current" disabled aria-label={plan.name + ' is your current plan'}>
                        <i data-lucide="check" aria-hidden="true"></i><span>Current Plan</span>
                      </button>
                      <p>Your subscription is billed {currentBillingInterval === 'annual' ? 'annually' : 'monthly'}.</p>
                    </React.Fragment>
                  : upgradeAvailable
                    ? <button
                        type="button"
                        className="rl-btn rl-btn--primary rl-checkout-plan__cta rl-checkout-plan__polish-action"
                        disabled={busy || upgradeBusy || !presentation}
                        onClick={() => onChooseUpgrade(plan.planKey)}>
                        {upgradeFlow && upgradeFlow.targetPlanKey === plan.planKey && upgradeBusy
                          ? 'Upgrading...'
                          : activeRedesign ? 'Upgrade' : 'Upgrade to ' + plan.name}
                      </button>
                  : planChangeUnavailable
                    ? <button type="button" className="rl-btn rl-checkout-plan__cta rl-checkout-plan__polish-action rl-checkout-plan__cta--unavailable" disabled title={unavailableCopy + '.'}>{unavailableCopy}</button>
                    : <button
                        type="button"
                        className="rl-btn rl-btn--primary rl-checkout-plan__cta"
                        disabled={busy || !presentation}
                        onClick={() => onChoosePlan(plan.planKey, retryWithNewKey)}>
                        {selectedAttempt && checkoutState.status === 'creating'
                          ? 'Redirecting to checkout...'
                          : retryWithNewKey
                            ? 'Try again'
                            : freeRedesign ? 'Upgrade' : 'Subscribe to ' + plan.name}
                      </button>}
              </div>
              <div className="rl-checkout-plan__secondary-slot">
                {plan.planKey === 'scale' && <a className="rl-btn rl-btn--secondary rl-checkout-plan__polish-action rl-checkout-plan__sales" href={TALK_TO_SALES_URL} target="_blank" rel="noopener noreferrer">Talk to sales</a>}
              </div>
            </div>
            {presentation && <ul className="rl-checkout-plan__capacities">
              {(activeRedesign
                ? getActiveBillingCardFeatures(plan, presentation)
                : [presentation.articles, presentation.users, presentation.websites, presentation.icpProfiles]
              ).map((capacity) =>
                <li key={capacity}><i data-lucide="check" aria-hidden="true"></i><span>{capacity}</span></li>)}
            </ul>}
          </article>;
        })}
      </div>
      {checkoutState.message && <p className="rl-checkout-message" role={checkoutState.status === 'error' || checkoutState.status === 'terminal' ? 'alert' : 'status'}>{checkoutState.message}</p>}
      <button
        type="button"
        className="rl-checkout-comparison-toggle"
        aria-expanded={featuresExpanded}
        aria-controls="checkout-feature-comparison"
        onClick={() => setFeaturesExpanded((expanded) => !expanded)}>
        <span>{featuresExpanded ? 'Hide all features' : 'Show all features'}</span>
        <i data-lucide={featuresExpanded ? 'chevron-up' : 'chevron-down'} aria-hidden="true"></i>
      </button>
      {featuresExpanded && <div className="rl-checkout-comparison" id="checkout-feature-comparison">
        <div className="rl-checkout-comparison__scroll">
          <table>
            <thead>
              <tr>
                <th scope="col">{activeRedesign ? <span className="rl-billing-active__visually-hidden">Feature</span> : 'Feature'}</th>
                {catalog.plans.map((plan) => <th scope="col" key={plan.planKey} className={plan.recommended ? 'rl-checkout-comparison__popular-column' : ''}>
                  {activeRedesign ? <>
                    <span className="rl-checkout-comparison__plan-name">{plan.name}</span>
                    <span className="rl-checkout-comparison__badge-slot">{plan.recommended && <small>Most popular</small>}</span>
                  </> : <>
                    <span>{plan.name}</span>
                    {plan.recommended && <small>Most Popular</small>}
                  </>}
                </th>)}
              </tr>
            </thead>
            <tbody>
              {comparisonGroups.map((group) => <React.Fragment key={group.title}>
                <tr className="rl-checkout-comparison__group"><th scope="rowgroup" colSpan={catalog.plans.length + 1}>{group.title}</th></tr>
                {group.rows.map((row, rowIndex) => <tr key={group.title + ':' + row.label} className={activeRedesign && rowIndex % 2 === 0 ? 'rl-checkout-comparison__stripe' : ''}>
                  <th scope="row">{row.label}</th>
                  {row.values.map((value, index) => <td key={catalog.plans[index].planKey} className={catalog.plans[index].recommended ? 'rl-checkout-comparison__popular-column' : ''}>
                    <CheckoutComparisonValue value={value} activeRedesign={activeRedesign} />
                  </td>)}
                </tr>)}
              </React.Fragment>)}
            </tbody>
          </table>
        </div>
      </div>}
    </section>
  );
}

function CheckoutReturnNotice({ state, onRetry, onGoHome }) {
  const status = state && state.status || 'idle';
  if (status === 'idle') return null;
  let title = '';
  let supporting = '';
  if (status === 'confirming') title = 'Confirming your subscription…';
  if (status === 'ready') {
    title = 'Your Workspace is ready.';
    supporting = 'Your subscription is active and your articles are ready to use.';
  }
  if (status === 'canceled') title = 'Checkout canceled. No changes were made.';
  if (status === 'still_confirming') {
    title = 'We’re still confirming your subscription.';
    supporting = 'This can take a little longer sometimes. Try again in a moment.';
  }
  if (status === 'error') {
    title = 'We couldn’t confirm your subscription right now.';
    supporting = 'Try again in a moment. No changes will be made from this page.';
  }
  return <div className="rl-checkout-return" role={status === 'error' ? 'alert' : 'status'} aria-live="polite" data-checkout-return-state={status}>
    <div>
      <h3>{title}</h3>
      {supporting && <p>{supporting}</p>}
    </div>
    {status === 'ready' && <button type="button" className="rl-btn rl-btn--secondary" onClick={onGoHome}>Go to Home</button>}
    {(status === 'still_confirming' || status === 'error') && <button type="button" className="rl-btn rl-btn--secondary" onClick={onRetry}>Check again</button>}
  </div>;
}

function SubscriptionUpgradeDialog({ flow, onClose, onConfirm, onRetry, onManageBilling }) {
  const dialogRef = useRef(null);
  const closeButtonRef = useRef(null);
  const contentRef = useRef(null);
  const [elapsed, setElapsed] = useState(0);
  const busy = !!(flow && ['submitting', 'authenticating', 'confirming'].includes(flow.status));
  const runtime = getWorkspaceCommercialRuntime();
  useEffect(() => {
    if (!busy || !flow.startedAt) { setElapsed(0); return undefined; }
    const tick = () => setElapsed(Math.max(0, Date.now() - flow.startedAt));
    tick();
    const timer = setInterval(tick, 100);
    return () => clearInterval(timer);
  }, [busy, flow && flow.startedAt]);
  const loading = busy && elapsed >= 1000;
  const resultState = !!flow && ['success', 'payment_method_required', 'processing_failure', 'provisioning_failed'].includes(flow.status);
  React.useLayoutEffect(() => {
    if (!flow || !dialogRef.current || !contentRef.current) return undefined;
    const dialog = dialogRef.current;
    const resize = () => {
      const style = window.getComputedStyle(dialog);
      const chrome = ['paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth']
        .reduce((sum, key) => sum + (parseFloat(style[key]) || 0), 0);
      dialog.style.height = Math.ceil(contentRef.current.getBoundingClientRect().height + chrome) + 'px';
    };
    resize();
    const observer = typeof window.ResizeObserver === 'function' ? new window.ResizeObserver(resize) : null;
    if (observer) observer.observe(contentRef.current);
    window.addEventListener('resize', resize);
    return () => { if (observer) observer.disconnect(); window.removeEventListener('resize', resize); };
  }, [flow && flow.status, loading]);
  useEffect(() => {
    if (!flow) return undefined;
    const dialog = dialogRef.current;
    const initial = busy ? dialog : dialog.querySelector('[data-upgrade-action]') || closeButtonRef.current || dialog;
    initial.focus();
    const handleKeyDown = (event) => {
      if (event.key === 'Escape') { if (busy) event.preventDefault(); else onClose(); }
    };
    const containFocus = (event) => { if (!dialog.contains(event.target)) initial.focus(); };
    document.addEventListener('keydown', handleKeyDown);
    document.addEventListener('focusin', containFocus);
    return () => { document.removeEventListener('keydown', handleKeyDown); document.removeEventListener('focusin', containFocus); };
  }, [flow && flow.status, busy, loading]);
  if (!flow) return null;
  const terminal = resultState;
  const title = flow.status === 'success'
    ? 'Your upgrade is complete'
    : flow.status === 'provisioning_failed' ? 'We received your payment'
    : flow.status === 'processing_failure' ? "We couldn't process your payment"
    : flow.status === 'payment_method_required'
      ? 'Update your payment method'
      : flow.status === 'failed' || flow.status === 'expired'
        ? 'Your upgrade wasn’t completed'
        : 'Confirm your upgrade';
  let message = '';
  if (flow.status === 'payment_method_required') message = runtime.upgradePaymentProblemMessage(flow.paymentProblem);
  if (flow.status === 'processing_failure') message = "Your current plan hasn't changed. Please try again. If this continues, contact our support team.";
  if (flow.status === 'provisioning_failed') message = "Your payment was successful, but we couldn't finish updating your Clicklyx plan. Please contact our support team so we can complete your upgrade. Do not try the upgrade again.";
  if (flow.status === 'success') message = `You're now on the ${flow.targetPlanName} plan. Your Articles have been updated, and your next renewal is scheduled for ${flow.periodEndLabel}.`;
  return <div className='rl-settings-modal-scrim rl-settings-modal-scrim--confirm' onMouseDown={busy ? undefined : onClose}>
    <div ref={dialogRef} className='rl-settings-modal rl-upgrade-modal' role='dialog' aria-modal='true' aria-label={loading ? 'Confirm your upgrade' : undefined} aria-labelledby={loading ? undefined : 'settings-subscription-upgrade-title'} aria-busy={busy || undefined} tabIndex={-1} data-upgrade-state={flow.status} data-upgrade-loading={loading || undefined} onMouseDown={(event) => event.stopPropagation()} onKeyDown={(event) => {
      if (event.key === 'Tab' && loading) { event.preventDefault(); dialogRef.current.focus(); }
      else trapFocusInDialog(event, dialogRef.current);
    }}>
      <div ref={contentRef} className='rl-upgrade-content'>
      {!busy && !terminal && <button ref={closeButtonRef} type='button' className='rl-settings-modal__close' onClick={onClose} aria-label='Close upgrade confirmation'><i data-lucide='x'></i></button>}
      {loading ? <div className='rl-upgrade-loading' role='status' aria-live='polite'>
        <span className='rl-cancellation-spinner' aria-hidden='true'></span>
        <p>{runtime.upgradeConfirmationMessage(elapsed)}</p>
      </div> : <>
      <div className='rl-settings-modal__head'>
        <h2 id='settings-subscription-upgrade-title'>{title}</h2>
        {message && <p role={flow.status === 'error' || flow.status === 'failed' ? 'alert' : 'status'}>{message}</p>}
      </div>
      {!terminal && <div className='rl-upgrade-summary'>
        <div><span>Current plan</span><strong>{flow.currentPlanName}</strong></div>
        <div><span>New plan</span><strong>{flow.targetPlanName}</strong></div>
        <div><span>Charged immediately</span><strong>{flow.amountLabel}</strong></div>
        <div><span>Next billing date</span><strong>{flow.periodEndLabel}</strong></div>
      </div>}
      {!terminal && <ul className='rl-upgrade-facts'>
        <li><i data-lucide='check' aria-hidden='true'></i><span>Your new billing cycle starts today.</span></li>
        <li><i data-lucide='check' aria-hidden='true'></i><span>You’ll keep any unused Articles from the {flow.currentPlanName} plan until {flow.periodEndLabel}.</span></li>
        <li><i data-lucide='check' aria-hidden='true'></i><span>You’ll receive {flow.allowanceArticles} Articles from the {flow.targetPlanName} plan today.</span></li>
      </ul>}
      {!terminal && flow.retentionDiscountActive && <p className='rl-upgrade-discount-notice'><i data-lucide='badge-percent' aria-hidden='true'></i><span>Your current retention discount will end when you upgrade. The amount above is the full list price.</span></p>}
      <div className='rl-settings-modal__actions'>
        {(flow.status === 'confirm' || busy) && <>
          <button type='button' className='rl-btn rl-btn--secondary' disabled={busy} onClick={onClose}>Not now</button>
          <button type='button' className='rl-btn rl-btn--primary' disabled={busy} onClick={() => onConfirm(false)}>Upgrade to {flow.targetPlanName}</button>
        </>}
        {flow.status === 'processing_failure' && flow.retrySafe && <>
          <button type='button' className='rl-btn rl-btn--secondary' onClick={onClose}>Close</button>
          <button type='button' className='rl-btn rl-btn--primary' data-upgrade-action onClick={() => onRetry(true)}>Try again</button>
        </>}
        {flow.status === 'payment_method_required' && <>
          <button type='button' className='rl-btn rl-btn--secondary' onClick={onClose}>Not now</button>
          <button type='button' className='rl-btn rl-btn--primary' data-upgrade-action onClick={onManageBilling}>Update payment method</button>
        </>}
        {(flow.status === 'failed' || flow.status === 'expired') && <button type='button' className='rl-btn rl-btn--primary' onClick={onClose}>Close</button>}
        {flow.status === 'provisioning_failed' && <a className='rl-btn rl-btn--primary' data-upgrade-action href='https://clicklyx.com/contact-support/' target='_blank' rel='noopener noreferrer'>Contact support</a>}
        {flow.status === 'success' && <button type='button' className='rl-btn rl-btn--primary' data-upgrade-action onClick={onClose}>Done</button>}
      </div>
      </>}
      </div>
    </div>
  </div>;
}

function AccountEmailChangePanel({ loginEmail, userId, disabled, reverify, runSensitiveAction, onConfirmed }) {
  const [open, setOpen] = useState(false);
  const [view, setView] = useState(null);
  const [email, setEmail] = useState('');
  const [code, setCode] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [completed, setCompleted] = useState(false);
  const operation = useRef(0);
  const inFlight = useRef(false);
  const emailInput = useRef(null);
  const codeInput = useRef(null);
  const changeButton = useRef(null);
  const doneButton = useRef(null);
  const returnFocus = useRef(false);
  useLucide([completed]);
  useEffect(() => () => { operation.current += 1; }, []);
  useEffect(() => {
    operation.current += 1;
    setOpen(false); setView(null); setEmail(''); setCode(''); setError(''); setCompleted(false); setBusy(false);
  }, [userId]);
  useEffect(() => {
    if (completed) doneButton.current?.focus();
    else if (open) (view?.pending?.email ? codeInput : emailInput).current?.focus();
    else if (returnFocus.current) { changeButton.current?.focus(); returnFocus.current = false; }
  }, [open, view?.pending, completed]);
  const safeMessage = (failure) => failure?.publicMessage || 'The email change could not be completed. Check its current status before retrying.';
  const run = async (action) => {
    if (inFlight.current) return;
    inFlight.current = true;
    const token = ++operation.current;
    setBusy(true); setError(''); setCompleted(false);
    try {
      const result = await action();
      if (operation.current !== token) return;
      if (userId && result.identity?.userId !== userId) throw createSettingsPublicError('Your signed-in account changed. Reopen Settings before continuing.', 'email_identity_changed');
      if (result.complete) {
        onConfirmed(result); setOpen(false); setView(null); setEmail(''); setCode('');
        setCompleted(true);
      } else { setView(result); }
    } catch (failure) {
      if (operation.current !== token) return;
      setCode(''); setError(safeMessage(failure));
      // Read back partial completion; never repeat a provider write automatically.
      if (view?.identity && failure?.code !== 'email_identity_changed' && failure?.code !== 'signed_out') {
        try {
          const latest = await window.RankLyxAuth.getCurrentUserEmailChange(view.identity);
          if (operation.current === token) setView(latest);
        } catch (_) { /* Keep the safe original error and require an explicit status check. */ }
      }
    } finally {
      inFlight.current = false;
      if (operation.current === token) setBusy(false);
    }
  };
  const load = () => { setOpen(true); return run(() => window.RankLyxAuth.getCurrentUserEmailChange()); };
  const start = (event) => {
    event.preventDefault();
    if (!view?.identity || disabled) return;
    const identity = view.identity;
    const replacement = email;
    return run(async () => {
      await reverify();
      return runSensitiveAction(() => window.RankLyxAuth.beginCurrentUserEmailChange(identity, replacement));
    });
  };
  const finish = (event) => {
    event.preventDefault();
    if (disabled) return;
    const verificationCode = code;
    setCode('');
    return run(() => runSensitiveAction(() => window.RankLyxAuth.completeCurrentUserEmailChange(view.identity, verificationCode)));
  };
  const cancel = () => run(async () => {
    const result = await runSensitiveAction(() => window.RankLyxAuth.cancelCurrentUserEmailChange(view.identity));
    setEmail(''); setCode(''); return result;
  });
  const pending = view?.pending;
  const close = () => { returnFocus.current = true; setOpen(false); setCompleted(false); setCode(''); setEmail(''); };
  const cancelAction = <button id='settings-email-cancel' type='button' className='rl-btn rl-settings-email__quiet' disabled={busy} onClick={pending ? cancel : close}>Cancel</button>;
  if (completed) return <div className='rl-settings-email-flow rl-settings-email-success'>
    <div className='rl-settings-email-success__message' role='status'>
      <span aria-hidden='true'><i data-lucide='circle-check'></i></span>
      <p id='settings-email-success-message'>Your email address has been changed successfully.</p>
    </div>
    <button id='settings-email-done' ref={doneButton} type='button' className='rl-btn rl-btn--primary' aria-describedby='settings-email-success-message' onClick={close}>Done</button>
  </div>;
  return <div className='rl-settings-email-flow'>
    {(!open || !pending?.email) && <div className='rl-settings-email-row'>
      <SettingsField label='Login email'><input className='rl-input' type='email' value={view?.email || loginEmail} readOnly aria-readonly='true' /></SettingsField>
      {!open && <button id='settings-change-email' ref={changeButton} type='button' className='rl-btn rl-btn--secondary' onClick={load} disabled={busy || disabled}>Change email</button>}
    </div>}
    {(!open || !pending?.email) && <p className='rl-settings-helper rl-settings-email__help'>Changes apply to your account across all Workspaces. Billing contacts and pending invitations stay unchanged.</p>}
    {disabled && <p className='rl-settings-helper'>Save or discard your profile edits before changing your email.</p>}
    {open && <div className='rl-settings-email-steps' aria-busy={busy}>
      {!view && <p className='rl-settings-helper'>{busy ? 'Loading your current account...' : 'Check your current account before continuing.'}</p>}
      {view && !pending && !view.supported && <p role='status' className='rl-settings-helper'>Your current email must be verified and must not be managed by a connected sign-in provider. Contact support if you need help changing it.</p>}
      {view && (!pending || !pending.email) && (view.supported || pending) && <form className='rl-settings-email-form' onSubmit={start}>
        <label className='rl-settings-dialog-field rl-settings-email-field' htmlFor='settings-new-email'><span>New email address</span><input id='settings-new-email' ref={emailInput} className='rl-input' type='email' autoComplete='email' aria-describedby='settings-email-start-help' required maxLength={254} value={email} onChange={(event) => setEmail(event.target.value)} disabled={busy} /></label>
        {pending && <p className='rl-settings-helper'>A previous attempt is incomplete. Enter the same replacement address to continue, or cancel that change.</p>}
        <p id='settings-email-start-help' className='rl-settings-helper rl-settings-email__help'>Confirm it’s you, then verify your new address. Your current email stays usable until the change is confirmed.</p>
        <div className='rl-settings-email-actions'>
          <button id='settings-email-send' type='submit' className='rl-btn rl-btn--primary' disabled={busy || disabled}>{busy ? 'Continuing...' : 'Continue'}</button>
          {cancelAction}
        </div>
      </form>}
      {pending?.email && <form className='rl-settings-email-form' onSubmit={finish}>
        <p id='settings-email-verification-help' className='rl-settings-helper rl-settings-email__help'>{pending.promoted ? 'Your verified new email is primary. Finish the change to confirm removal of the previous address and refresh your profile.' : pending.verified ? 'Your new email is verified. Finish the change to make it primary and remove the previous address.' : 'Enter the verification code Clerk sent to:'}<strong className='rl-settings-email-destination'>{pending.email}</strong></p>
        {!pending.verified && <label className='rl-settings-dialog-field rl-settings-email-code-field' htmlFor='settings-email-code'><span>Verification code</span><input id='settings-email-code' ref={codeInput} className='rl-input' type='text' inputMode='numeric' autoComplete='one-time-code' aria-describedby='settings-email-verification-help' pattern='[0-9]{6}' required maxLength={6} value={code} onChange={(event) => setCode(event.target.value)} disabled={busy} /></label>}
        <div className='rl-settings-email-actions'>
          <button id='settings-email-finish' type='submit' className='rl-btn rl-btn--primary' disabled={busy || disabled}>{busy ? 'Continuing...' : pending.verified ? 'Finish email change' : 'Verify email'}</button>
          {!pending.verified && <button id='settings-email-resend' type='button' className='rl-btn rl-btn--secondary' disabled={busy} onClick={() => run(() => runSensitiveAction(() => window.RankLyxAuth.resendCurrentUserEmailChange(view.identity)))}>Resend code</button>}
          {!pending.promoted && cancelAction}
        </div>
      </form>}
      {(!view || (!pending && !view.supported)) && <div className='rl-settings-email-actions'>{cancelAction}</div>}
      <details className='rl-settings-email-recovery'>
        <summary id='settings-email-recovery-toggle'>Having trouble?</summary>
        <p className='rl-settings-helper'>Check the current status before retrying an incomplete change.</p>
        <div className='rl-settings-email-actions'>
          <button id='settings-email-status' type='button' className='rl-btn rl-settings-email__quiet' disabled={busy} onClick={load}>Check current status</button>
          {pending && <button id='settings-email-close' type='button' className='rl-btn rl-settings-email__quiet' disabled={busy} onClick={close}>Close for now</button>}
        </div>
      </details>
    </div>}
    {error && <p className='rl-settings-dialog-error' role='alert'>{error}</p>}
  </div>;
}

function SettingsPage({ user, workspace, creditState, commercialState, refreshCommercial, refreshWorkspaceReads, checkoutReturn, requestedSection, onNavigate, onSaveProfile, onSaveWorkspace, onUpgradeComplete }) {
  const workspaceAccess = useWorkspaceAccessUi();
  const workspaceScopeActiveRef = useRef(true);
  const workspaceScopeId = getWorkspaceDirectoryId(workspace);
  const workspaceScopeCurrent = () => workspaceScopeActiveRef.current && settingsMountedRef.current
    && getWorkspaceDirectoryId(window.currentWorkspace || workspace) === workspaceScopeId;
  const workspaceActionAllowed = (capability) => workspaceScopeCurrent() && workspaceAdmin
    && isWorkspaceAdminRole((window.currentWorkspace || workspace).role)
    && workspaceAccess.workspaceId === workspaceScopeId && workspaceAccess.allows(capability);
  const [selected, setSelected] = useState(() => normalizeSettingsSectionId(requestedSection && requestedSection.section));
  const committedSettingsSectionRef = useRef(selected === 'billing' ? null : selected);
  const [profileDraft, setProfileDraft] = useState(user);
  const [workspaceDraft, setWorkspaceDraft] = useState(workspace);
  const [workspaceSavedDraft, setWorkspaceSavedDraft] = useState(workspace);
  const [workspaceDirectory, setWorkspaceDirectory] = useState(() => createWorkspaceDirectoryState(getWorkspaceDirectoryId(workspace)));
  const [workspaceDirectoryRetryToken, setWorkspaceDirectoryRetryToken] = useState(0);
  const [workspaceInviteDialogOpen, setWorkspaceInviteDialogOpen] = useState(false);
  const [workspaceInviteForm, setWorkspaceInviteForm] = useState(createWorkspaceInvitationFormState);
  const [workspaceInvitationNotice, setWorkspaceInvitationNotice] = useState('');
  const [workspaceCancelInvitation, setWorkspaceCancelInvitation] = useState(null);
  const [workspaceCancelInvitationBusy, setWorkspaceCancelInvitationBusy] = useState(false);
  const [workspaceCancelInvitationError, setWorkspaceCancelInvitationError] = useState('');
  const [workspaceMemberNotice, setWorkspaceMemberNotice] = useState('');
  const [workspaceMemberError, setWorkspaceMemberError] = useState('');
  const [workspaceMemberAction, setWorkspaceMemberAction] = useState({ membershipId: '', mode: '' });
  const [workspaceMemberMutationRuntimeReady, setWorkspaceMemberMutationRuntimeReady] = useState(() => isWorkspaceMemberMutationRuntimeAvailable());
  const [workspaceRemoveMember, setWorkspaceRemoveMember] = useState(null);
  const [workspaceRemoveMemberBusy, setWorkspaceRemoveMemberBusy] = useState(false);
  const [workspaceRemoveMemberError, setWorkspaceRemoveMemberError] = useState('');
  const [workspaceSettingsSwitchingId, setWorkspaceSettingsSwitchingId] = useState('');
  const [workspaceSettingsSwitchError, setWorkspaceSettingsSwitchError] = useState('');
  const [saved, setSaved] = useState('');
  const [billingPortalState, setBillingPortalState] = useState({ status: 'idle', error: '' });
  const [usedSeatState, setUsedSeatState] = useState({ workspaceId: '', status: 'idle', count: null });
  const [checkoutBillingInterval, setCheckoutBillingInterval] = useState('monthly');
  const [checkoutState, setCheckoutState] = useState({ status: 'idle', workspaceId: '', planKey: '', billingInterval: 'monthly', message: '' });
  const [upgradeConfirmation, setUpgradeConfirmation] = useState(null);
  const [checkoutReturnState, setCheckoutReturnState] = useState({ status: 'idle', workspaceId: '', errorCode: '' });
  const [subscriptionConfirmation, setSubscriptionConfirmation] = useState(null);
  const [subscriptionMutationState, setSubscriptionMutationState] = useState({ status: 'idle', workspaceId: '', desiredCancellationScheduled: null, error: '' });
  const [profileSaveFeedback, setProfileSaveFeedback] = useState('idle');
  const [workspaceSaveFeedback, setWorkspaceSaveFeedback] = useState('idle');
  const [profileError, setProfileError] = useState('');
  const [accountSecurity, setAccountSecurity] = useState(() => normalizeAccountSecurityStateForUi(null, user && user.email));
  const [accountSecurityError, setAccountSecurityError] = useState('');
  const [accountSecurityNotice, setAccountSecurityNotice] = useState('');
  const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);
  const [sessionsDialogOpen, setSessionsDialogOpen] = useState(false);
  const [sessionsState, setSessionsState] = useState({ loading: false, sessions: [], currentSessionId: '', error: '', notice: '', failures: [] });
  const [sessionConfirmation, setSessionConfirmation] = useState(null);
  const [sessionActionBusy, setSessionActionBusy] = useState(false);
  const [mfaDialogOpen, setMfaDialogOpen] = useState(false);
  const [mfaRemoveOpen, setMfaRemoveOpen] = useState(false);
  const [mfaRemoveBusy, setMfaRemoveBusy] = useState(false);
  const [mfaRemoveError, setMfaRemoveError] = useState('');
  const [reverificationRequest, setReverificationRequest] = useState(null);
  const [workspaceError, setWorkspaceError] = useState('');
  const [loadingWorkspace, setLoadingWorkspace] = useState(false);
  const [savingWorkspace, setSavingWorkspace] = useState(false);
  const [workspaceLoaded, setWorkspaceLoaded] = useState(false);
  const [workspaceLoadFailed, setWorkspaceLoadFailed] = useState(false);
  const [workspaceLoadRetryToken, setWorkspaceLoadRetryToken] = useState(0);
  const [savingProfile, setSavingProfile] = useState(false);
  const [pendingAvatarFile, setPendingAvatarFile] = useState(null);
  const [pendingAvatarUrl, setPendingAvatarUrl] = useState('');
  const [pendingAvatarRemoval, setPendingAvatarRemoval] = useState(false);
  const [pendingWorkspaceLogoFile, setPendingWorkspaceLogoFile] = useState(null);
  const [pendingWorkspaceLogoUrl, setPendingWorkspaceLogoUrl] = useState('');
  const [pendingWorkspaceLogoRemoval, setPendingWorkspaceLogoRemoval] = useState(false);
  const avatarInputRef = useRef(null);
  const workspaceLogoInputRef = useRef(null);
  const pendingAvatarUrlRef = useRef('');
  const pendingWorkspaceLogoUrlRef = useRef('');
  const workspaceDirtyRef = useRef(false);
  const workspaceLoadRequestRef = useRef(0);
  const workspaceLoadInFlightRef = useRef(false);
  const workspaceDirectoryRequestRef = useRef(0);
  const workspaceDirectoryLoadInFlightRef = useRef(false);
  const workspaceInviteButtonRef = useRef(null);
  const workspaceInviteEmailRef = useRef(null);
  const workspaceInvitationMutationRequestRef = useRef(0);
  const workspaceInvitationMutationBusyRef = useRef(false);
  const workspaceMemberMutationRequestRef = useRef(0);
  const workspaceMemberMutationBusyRef = useRef(false);
  const billingPortalInFlightRef = useRef(false);
  const checkoutCoordinatorRef = useRef(null);
  const checkoutCadenceInitializedRef = useRef(false);
  const upgradeCoordinatorRef = useRef(null);
  const upgradeRunRef = useRef(false);
  const upgradeRetryAllowedRef = useRef(false);
  const checkoutReturnCoordinatorRef = useRef(null);
  const checkoutScopeRef = useRef({ workspaceId: '', administrator: false });
  const upgradeScopeRef = useRef({ workspaceId: '', administrator: false });
  const subscriptionMutationCoordinatorRef = useRef(null);
  const subscriptionMutationScopeRef = useRef({ workspaceId: '', administrator: false });
  const workspaceMemberships = useWorkspaceMemberships(workspace, selected === 'workspace');
  const accountSecurityRequestRef = useRef(0);
  const sessionsRequestRef = useRef(0);
  const settingsMountedRef = useRef(true);
  const profileSaveFeedbackTimerRef = useRef(null);
  const workspaceSaveFeedbackTimerRef = useRef(null);
  const reverificationPromiseRef = useRef(null);

  if (!subscriptionMutationCoordinatorRef.current) {
    const commercialRuntime = getWorkspaceCommercialRuntime();
    if (commercialRuntime && typeof commercialRuntime.createSubscriptionMutationCoordinator === 'function') {
      subscriptionMutationCoordinatorRef.current = commercialRuntime.createSubscriptionMutationCoordinator((endpoint, options) => {
        const auth = window.RankLyxAuth;
        if (!auth || typeof auth.authenticatedFetch !== 'function') {
          return Promise.reject(new Error('Authenticated subscription changes are unavailable.'));
        }
        return auth.authenticatedFetch(endpoint, options);
      });
    }
  }
  if (!checkoutCoordinatorRef.current) {
    const commercialRuntime = getWorkspaceCommercialRuntime();
    if (commercialRuntime && typeof commercialRuntime.createCheckoutAttemptCoordinator === 'function') {
      checkoutCoordinatorRef.current = commercialRuntime.createCheckoutAttemptCoordinator(
        (endpoint, options) => {
          const auth = window.RankLyxAuth;
          if (!auth || typeof auth.authenticatedFetch !== 'function') {
            return Promise.reject(new Error('Authenticated Checkout is unavailable.'));
          }
          return auth.authenticatedFetch(endpoint, options);
        },
        (url) => window.location.assign(url)
      );
    }
  }
  if (!upgradeCoordinatorRef.current) {
    const commercialRuntime = getWorkspaceCommercialRuntime();
    if (commercialRuntime && typeof commercialRuntime.createUpgradeAttemptCoordinator === 'function') {
      upgradeCoordinatorRef.current = commercialRuntime.createUpgradeAttemptCoordinator((endpoint, options) => {
        const auth = window.RankLyxAuth;
        if (!auth || typeof auth.authenticatedFetch !== 'function') {
          return Promise.reject(new Error('Authenticated subscription upgrades are unavailable.'));
        }
        return auth.authenticatedFetch(endpoint, options);
      });
    }
  }
  if (!checkoutReturnCoordinatorRef.current) {
    const returnRuntime = window.ClicklyxCheckoutReturn;
    if (returnRuntime && typeof returnRuntime.createCheckoutReturnCoordinator === 'function') {
      checkoutReturnCoordinatorRef.current = returnRuntime.createCheckoutReturnCoordinator();
    }
  }

  const clearPendingAvatarPreview = () => {
    if (pendingAvatarUrlRef.current && window.URL && typeof window.URL.revokeObjectURL === 'function') {
      window.URL.revokeObjectURL(pendingAvatarUrlRef.current);
    }
    pendingAvatarUrlRef.current = '';
    setPendingAvatarUrl('');
    setPendingAvatarFile(null);
  };
  const resetPendingAvatarState = () => {
    clearPendingAvatarPreview();
    setPendingAvatarRemoval(false);
  };
  const clearPendingWorkspaceLogoPreview = () => {
    if (pendingWorkspaceLogoUrlRef.current && window.URL && typeof window.URL.revokeObjectURL === 'function') {
      window.URL.revokeObjectURL(pendingWorkspaceLogoUrlRef.current);
    }
    pendingWorkspaceLogoUrlRef.current = '';
    setPendingWorkspaceLogoUrl('');
    setPendingWorkspaceLogoFile(null);
  };
  const resetPendingWorkspaceLogoState = () => {
    clearPendingWorkspaceLogoPreview();
    setPendingWorkspaceLogoRemoval(false);
  };
  const clearProfileSaveFeedbackTimer = () => {
    if (profileSaveFeedbackTimerRef.current) {
      window.clearTimeout(profileSaveFeedbackTimerRef.current);
      profileSaveFeedbackTimerRef.current = null;
    }
  };
  const clearWorkspaceSaveFeedbackTimer = () => {
    if (workspaceSaveFeedbackTimerRef.current) {
      window.clearTimeout(workspaceSaveFeedbackTimerRef.current);
      workspaceSaveFeedbackTimerRef.current = null;
    }
  };
  const clearProfileSaveFeedback = () => {
    clearProfileSaveFeedbackTimer();
    setProfileSaveFeedback('idle');
  };
  const clearWorkspaceSaveFeedback = () => {
    clearWorkspaceSaveFeedbackTimer();
    setWorkspaceSaveFeedback('idle');
  };
  const showProfileSavedFeedback = () => {
    clearProfileSaveFeedbackTimer();
    setProfileSaveFeedback('saved');
    profileSaveFeedbackTimerRef.current = window.setTimeout(() => {
      profileSaveFeedbackTimerRef.current = null;
      setProfileSaveFeedback('idle');
    }, 2000);
  };
  const showWorkspaceSavedFeedback = () => {
    clearWorkspaceSaveFeedbackTimer();
    setWorkspaceSaveFeedback('saved');
    workspaceSaveFeedbackTimerRef.current = window.setTimeout(() => {
      workspaceSaveFeedbackTimerRef.current = null;
      setWorkspaceSaveFeedback('idle');
    }, 2000);
  };

  useLucide([selected, profileDraft.avatarDataUrl, profileDraft.imageUrl, pendingAvatarUrl, pendingAvatarRemoval, workspaceDraft.logoDataUrl, workspaceDraft.imageUrl, pendingWorkspaceLogoUrl, pendingWorkspaceLogoRemoval, loadingWorkspace, savingWorkspace, accountSecurity, passwordDialogOpen, sessionsDialogOpen, sessionConfirmation, sessionsState, sessionActionBusy, mfaDialogOpen, mfaRemoveOpen, mfaRemoveBusy, mfaRemoveError, reverificationRequest, workspaceInviteDialogOpen, workspaceInviteForm, workspaceInvitationNotice, workspaceCancelInvitation, workspaceCancelInvitationBusy, workspaceCancelInvitationError, workspaceMemberNotice, workspaceMemberError, workspaceMemberAction, workspaceRemoveMember, workspaceRemoveMemberBusy, workspaceRemoveMemberError, workspaceMemberships.state, workspaceSettingsSwitchingId, workspaceSettingsSwitchError, subscriptionConfirmation, subscriptionMutationState, checkoutBillingInterval, checkoutState, upgradeConfirmation]);
  const profileNameParts = [
    String(profileDraft.firstName || '').trim(),
    String(profileDraft.lastName || '').trim()
  ].filter(Boolean);
  const profileName = profileNameParts.join(' ');
  const profileDisplayName = profileName || String(profileDraft.fullName || profileDraft.displayName || profileDraft.name || 'Account').trim() || 'Account';
  const profileInitials = getInitials(profileDisplayName, profileDraft.email);
  const workspaceInitials = getInitials(workspaceDraft.name, 'RL');
  const rawWorkspaceLogoUrl = workspaceDraft.logoDataUrl || workspaceDraft.logoUrl || workspaceDraft.imageUrl || '';
  const workspaceHasStoredLogo = workspaceDraft.hasImage === true && !!rawWorkspaceLogoUrl;
  const storedWorkspaceLogoUrl = workspaceHasStoredLogo ? rawWorkspaceLogoUrl : '';
  const workspaceLogoUrl = pendingWorkspaceLogoRemoval ? '' : pendingWorkspaceLogoUrl || storedWorkspaceLogoUrl;
  const workspaceAdmin = isWorkspaceAdminRole(workspace && workspace.role || workspaceSavedDraft.role || workspaceDraft.role);
  const settingsSections = SETTINGS_SECTIONS;
  const requestedSectionId = normalizeSettingsSectionId(selected, settingsSections);
  const workspaceCanEdit = workspaceLoaded && workspaceAdmin && workspaceActionAllowed('canMutateWorkspaceContent');
  const canRemoveWorkspaceLogo = workspaceCanEdit && !!(pendingWorkspaceLogoFile || (!pendingWorkspaceLogoRemoval && workspaceHasStoredLogo));
  const creditTotalText = getCreditMetricText(creditState, 'total');
  const creditConsumedText = getCreditMetricText(creditState, 'consumed');
  const creditRemainingText = getCreditMetricText(creditState, 'remaining');
  const creditStateMessage = getCreditStateMessage(creditState);
  const commercialPresentation = getCommercialPresentation(commercialState);
  const settingsWorkspaceId = getWorkspaceDirectoryId(workspace);
  const authoritativeSubscription = commercialState && commercialState.status === 'loaded' && commercialState.billing ? commercialState.billing.subscription : null;
  const checkoutCatalog = commercialState && commercialState.status === 'loaded' && commercialState.billing
    ? commercialState.billing.checkoutCatalog : null;
  const authoritativeUpgradeProjection = commercialState && commercialState.status === 'loaded' && commercialState.billing
    ? commercialState.billing.upgrade : null;
  const currentSubscriptionPresent = !!(authoritativeSubscription && authoritativeSubscription.commercialState === 'current');
  const checkoutHeading = currentSubscriptionPresent
    ? 'Compare plans'
    : authoritativeSubscription && authoritativeSubscription.present === true ? 'Subscribe again' : 'Choose a plan';
  const authoritativeRetentionOffer = commercialState && commercialState.status === 'loaded' && commercialState.billing
    ? commercialState.billing.retentionOffer : null;
  const commercialRuntime = getWorkspaceCommercialRuntime();
  const currentCheckoutPlanKey = commercialRuntime && typeof commercialRuntime.getCurrentCheckoutPlanKey === 'function'
    ? commercialRuntime.getCurrentCheckoutPlanKey(commercialState && commercialState.billing)
    : '';
  const currentCheckoutBillingInterval = authoritativeSubscription && authoritativeSubscription.billingInterval === 'year'
    ? 'annual'
    : 'monthly';
  const activeMemberCount = usedSeatState.workspaceId === settingsWorkspaceId && usedSeatState.status === 'loaded'
    ? usedSeatState.count : null;
  const billingReadReady = !!(commercialState && commercialState.status === 'loaded'
    && commercialState.billing && commercialState.billing.subscription);
  const billingReadLoading = !commercialState || ['idle', 'hidden', 'loading'].includes(commercialState.status);
  const healthyActiveBilling = commercialRuntime && typeof commercialRuntime.getHealthyActiveBillingPresentation === 'function'
    ? commercialRuntime.getHealthyActiveBillingPresentation(commercialState && commercialState.billing, Date.now(), activeMemberCount)
    : null;
  const scheduledCancellationBilling = commercialRuntime && typeof commercialRuntime.getScheduledCancellationBillingPresentation === 'function'
    ? commercialRuntime.getScheduledCancellationBillingPresentation(commercialState && commercialState.billing, Date.now(), activeMemberCount)
    : null;
  const freeBilling = commercialRuntime && typeof commercialRuntime.getFreeBillingPresentation === 'function'
    ? commercialRuntime.getFreeBillingPresentation(commercialState && commercialState.billing)
    : null;
  const redesignedBilling = healthyActiveBilling || scheduledCancellationBilling || freeBilling;
  const redesignedBillingState = healthyActiveBilling ? 'healthy-active'
    : scheduledCancellationBilling ? 'scheduled-cancellation'
      : freeBilling ? 'free' : '';
  const shouldLoadUsedSeats = requestedSectionId === 'billing' && workspaceAdmin
    && !!(healthyActiveBilling || scheduledCancellationBilling);
  const billingArticlesLoading = !freeBilling && (!creditState || ['idle', 'loading'].includes(creditState.status));
  const billingSeatsLoading = shouldLoadUsedSeats && (usedSeatState.workspaceId !== settingsWorkspaceId
    || ['idle', 'loading'].includes(usedSeatState.status));
  const checkoutReturnResolving = checkoutReturn && checkoutReturn.workspaceId === settingsWorkspaceId
    && ['idle', 'confirming'].includes(checkoutReturnState.status);
  const billingTransitionPending = requestedSectionId === 'billing' && workspaceAdmin
    && (billingReadLoading || (billingReadReady && (billingArticlesLoading || billingSeatsLoading || checkoutReturnResolving)));
  const selectedSectionId = billingTransitionPending ? committedSettingsSectionRef.current : requestedSectionId;
  const activeSection = settingsSections.find((section) => section.id === selectedSectionId) || settingsSections[0];
  useEffect(() => {
    if (!billingTransitionPending) committedSettingsSectionRef.current = selectedSectionId;
  }, [billingTransitionPending, selectedSectionId]);
  useEffect(() => {
    let current = true;
    if (!shouldLoadUsedSeats || !settingsWorkspaceId || !workspaceScopeCurrent()) {
      setUsedSeatState({ workspaceId: '', status: 'idle', count: null });
      return () => { current = false; };
    }
    setUsedSeatState({ workspaceId: settingsWorkspaceId, status: 'loading', count: null });
    const auth = window.RankLyxAuth;
    if (!auth || typeof auth.authenticatedFetch !== 'function') {
      setUsedSeatState({ workspaceId: settingsWorkspaceId, status: 'error', count: null });
      return () => { current = false; };
    }
    auth.authenticatedFetch(buildWorkspaceMembersDirectoryUrl({ limit: 1 }), { method: 'GET' })
      .then(parseWorkspaceMembersDirectoryResponse)
      .then((directory) => {
        const count = commercialRuntime.getActiveMemberCount(directory, settingsWorkspaceId);
        if (current && workspaceScopeCurrent()) {
          setUsedSeatState({ workspaceId: settingsWorkspaceId, status: 'loaded', count });
        }
      })
      .catch(() => {
        if (current && workspaceScopeCurrent()) {
          setUsedSeatState({ workspaceId: settingsWorkspaceId, status: 'error', count: null });
        }
      });
    return () => { current = false; };
  }, [shouldLoadUsedSeats, settingsWorkspaceId, workspaceAccess.status]);
  const subscriptionCancellationAction = commercialRuntime && typeof commercialRuntime.getSubscriptionCancellationAction === 'function'
    ? commercialRuntime.getSubscriptionCancellationAction(commercialState && commercialState.billing, Date.now())
    : null;
  const subscriptionPeriodEnd = subscriptionCancellationAction && subscriptionCancellationAction.periodEnd || '';
  const subscriptionPeriodEndLabel = subscriptionCancellationAction && subscriptionCancellationAction.periodEndLabel || '';
  const subscriptionCancellationScheduled = !!(authoritativeSubscription && authoritativeSubscription.cancellationScheduled === true);
  const subscriptionActionAvailable = !!(workspaceAdmin
    && settingsWorkspaceId
    && subscriptionCancellationAction);
  const subscriptionMutationBusy = ['submitting', 'pending'].includes(subscriptionMutationState.status);
  checkoutScopeRef.current = { workspaceId: settingsWorkspaceId, administrator: workspaceAdmin };
  upgradeScopeRef.current = { workspaceId: settingsWorkspaceId, administrator: workspaceAdmin };
  subscriptionMutationScopeRef.current = { workspaceId: settingsWorkspaceId, administrator: workspaceAdmin };
  useEffect(() => {
    setBillingPortalState({ status: 'idle', error: '' });
    checkoutCadenceInitializedRef.current = false;
    setCheckoutBillingInterval('monthly');
    const checkoutCoordinator = checkoutCoordinatorRef.current;
    if (checkoutCoordinator) checkoutCoordinator.reset(settingsWorkspaceId);
    setCheckoutState({ status: 'idle', workspaceId: settingsWorkspaceId, planKey: '', billingInterval: 'monthly', message: '' });
    const upgradeCoordinator = upgradeCoordinatorRef.current;
    if (upgradeCoordinator) upgradeCoordinator.reset(settingsWorkspaceId);
    upgradeRetryAllowedRef.current = false;
    setUpgradeConfirmation(null);
    const coordinator = subscriptionMutationCoordinatorRef.current;
    if (coordinator) coordinator.reset(settingsWorkspaceId);
    setSubscriptionConfirmation(null);
    setSubscriptionMutationState({ status: 'idle', workspaceId: '', desiredCancellationScheduled: null, error: '' });
  }, [settingsWorkspaceId, workspaceAdmin]);
  useEffect(() => {
    if (checkoutCadenceInitializedRef.current || !workspaceAdmin || !settingsWorkspaceId
      || !commercialState || commercialState.status !== 'loaded') return;
    const cadence = commercialRuntime && typeof commercialRuntime.getBillingComparisonCadence === 'function'
      ? commercialRuntime.getBillingComparisonCadence(commercialState.billing) : null;
    if (cadence) {
      checkoutCadenceInitializedRef.current = true;
      setCheckoutBillingInterval(cadence);
    }
  }, [settingsWorkspaceId, workspaceAdmin, commercialState && commercialState.status, currentCheckoutBillingInterval]);
  useEffect(() => {
    const coordinator = checkoutReturnCoordinatorRef.current;
    const marker = checkoutReturn && checkoutReturn.workspaceId === settingsWorkspaceId ? checkoutReturn : null;
    if (!coordinator || !marker || !workspaceAdmin || !settingsWorkspaceId) {
      if (coordinator) coordinator.cancel();
      setCheckoutReturnState({ status: 'idle', workspaceId: settingsWorkspaceId, errorCode: '' });
      return undefined;
    }
    const returnRuntime = window.ClicklyxCheckoutReturn;
    coordinator.start({
      marker,
      workspaceId: settingsWorkspaceId,
      isAdministrator: true,
      getWorkspaceId: () => getWorkspaceDirectoryId(window.currentWorkspace || workspace),
      confirmOperation: (operationId, signal) => {
        const authRuntime = window.RankLyxAuth;
        if (!returnRuntime || typeof returnRuntime.requestServerConfirmation !== 'function'
          || !authRuntime || typeof authRuntime.authenticatedFetch !== 'function') {
          return Promise.reject(new Error('Checkout confirmation is unavailable.'));
        }
        return returnRuntime.requestServerConfirmation(
          (endpoint, options) => authRuntime.authenticatedFetch(endpoint, options),
          operationId,
          signal
        );
      },
      refreshWorkspaceReads: (workspaceId) => {
        if (typeof refreshWorkspaceReads !== 'function') return Promise.reject(new Error('Workspace billing reads are unavailable.'));
        return refreshWorkspaceReads(workspaceId);
      },
      refreshBilling: (workspaceId) => {
        if (typeof refreshCommercial !== 'function') return Promise.reject(new Error('Workspace billing is unavailable.'));
        return refreshCommercial(workspaceId);
      },
      refreshAccess: (workspaceId) => {
        const accessClient = window.ClicklyxWorkspaceAccess;
        if (!accessClient || typeof accessClient.refresh !== 'function'
          || getWorkspaceDirectoryId(window.currentWorkspace || workspace) !== workspaceId) {
          return Promise.reject(new Error('Workspace access is unavailable.'));
        }
        return accessClient.refresh({ reason: 'checkout_confirmation' });
      },
      onUpdate: (nextState) => {
        if (!settingsMountedRef.current
          || getWorkspaceDirectoryId(window.currentWorkspace || workspace) !== settingsWorkspaceId) return;
        setCheckoutReturnState(nextState);
      }
    });
    return () => coordinator.cancel();
  }, [settingsWorkspaceId, workspaceAdmin, checkoutReturn && checkoutReturn.workspaceId]);
  useEffect(() => {
    if (subscriptionMutationState.status !== 'pending'
      || subscriptionMutationState.workspaceId !== settingsWorkspaceId
      || !authoritativeSubscription) return;
    if (authoritativeSubscription.cancellationScheduled === subscriptionMutationState.desiredCancellationScheduled) {
      if (!commercialRuntime.cancellationProjectionMatches(commercialState.billing,
        subscriptionMutationState.desiredCancellationScheduled, subscriptionMutationState.periodEnd)) return;
      setSubscriptionMutationState({ status: 'idle', workspaceId: '', desiredCancellationScheduled: null, error: '' });
      if (subscriptionConfirmation && ['cancel_sync_pending', 'reverse_sync_pending'].includes(subscriptionConfirmation.step)) {
        setSubscriptionConfirmation((current) => current ? {
          ...current,
          step: subscriptionMutationState.desiredCancellationScheduled ? 'cancel_success' : 'reverse_success',
          periodEnd: authoritativeSubscription.currentPeriod.end,
          periodEndLabel: commercialRuntime.formatBillingDate(authoritativeSubscription.currentPeriod.end)
        } : current);
      }
    }
  }, [commercialState, authoritativeSubscription && authoritativeSubscription.cancellationScheduled,
    authoritativeSubscription && authoritativeSubscription.currentPeriod && authoritativeSubscription.currentPeriod.end,
    settingsWorkspaceId, subscriptionMutationState.status, subscriptionMutationState.workspaceId,
    subscriptionMutationState.desiredCancellationScheduled, subscriptionMutationState.periodEnd, subscriptionConfirmation]);
  useEffect(() => {
    if (!subscriptionActionAvailable && subscriptionConfirmation && !subscriptionMutationBusy) setSubscriptionConfirmation(null);
  }, [subscriptionActionAvailable, subscriptionConfirmation, subscriptionMutationBusy]);
  const ownerName = profileDisplayName;
  const ownerEmail = String(profileDraft.email || '').trim();
  const profileSaved = user || {};
  const loginEmail = accountSecurity.email || profileDraft.email || '';
  const securityPasswordEnabled = accountSecurity.passwordEnabled === true;
  const securityTotpEnabled = accountSecurity.totpEnabled === true;
  const securityBackupCodeEnabled = accountSecurity.backupCodeEnabled === true;
  const securityMfaFeatureEnabled = accountSecurity.mfaFeatureEnabled === true;
  const mfaRowCanOpen = securityMfaFeatureEnabled || securityTotpEnabled;
  const connectedProviderText = formatConnectedProviderText(accountSecurity.externalAccounts);
  const passwordRowDescription = securityPasswordEnabled ? 'Use a strong password that you do not reuse elsewhere.' : 'Your account currently uses a connected sign-in provider.';
  const passwordRowAction = securityPasswordEnabled ? 'Change password' : 'Add password';
  const mfaRowDescription = securityTotpEnabled ? 'Your account is protected with an authenticator app.' : 'Add an authenticator app and recovery codes for extra account security.';
  const mfaRowStatus = securityTotpEnabled ? 'Enabled' : securityMfaFeatureEnabled ? 'Not enabled' : 'Coming soon';
  const mfaRowAction = securityTotpEnabled ? 'Manage MFA' : securityMfaFeatureEnabled ? 'Set up MFA' : 'Coming soon';
  const mfaRowDisabled = accountSecurity.loading || !mfaRowCanOpen;
  const storedAvatarUrl = profileDraft.avatarDataUrl || profileDraft.imageUrl || '';
  const profileAvatarUrl = pendingAvatarRemoval ? '' : pendingAvatarUrl || storedAvatarUrl;
  const profileHasStoredImage = !!(profileDraft.hasImage && storedAvatarUrl);
  const canRemoveAvatar = !!(pendingAvatarFile || (!pendingAvatarRemoval && profileHasStoredImage));
  const profileChanged =
    String(profileDraft.firstName || '').trim() !== String(profileSaved.firstName || '').trim() ||
    String(profileDraft.lastName || '').trim() !== String(profileSaved.lastName || '').trim() ||
    !!pendingAvatarFile ||
    !!pendingAvatarRemoval;
  const profileSaveDisabled = !profileChanged || savingProfile || profileSaveFeedback === 'saved';
  const profileSaveButtonLabel = savingProfile ? 'Saving...' : profileSaveFeedback === 'saved' ? 'Saved' : 'Save changes';
  const workspaceSavedName = String(workspaceSavedDraft.name || '').trim();
  const workspaceSavedWebsite = String(workspaceSavedDraft.website || workspaceSavedDraft.websiteUrl || '').trim();
  const workspaceDraftName = String(workspaceDraft.name || '').trim();
  const workspaceDraftWebsite = String(workspaceDraft.website || workspaceDraft.websiteUrl || '').trim();
  const workspaceChanged = workspaceCanEdit && (
    workspaceDraftName !== workspaceSavedName ||
    workspaceDraftWebsite !== workspaceSavedWebsite ||
    !!pendingWorkspaceLogoFile ||
    !!pendingWorkspaceLogoRemoval
  );
  const workspaceSaveDisabled = !workspaceLoaded || loadingWorkspace || savingWorkspace || workspaceSaveFeedback === 'saved' || !workspaceCanEdit || !workspaceChanged;
  const workspaceSaveButtonLabel = savingWorkspace ? 'Saving...' : workspaceSaveFeedback === 'saved' ? 'Saved' : 'Save changes';
  const workspaceRoleLabel = getWorkspaceRoleLabel(workspaceDirectory.role || workspaceDraft.role);
  const workspaceDirectoryWorkspaceId = getWorkspaceDirectoryId(workspace) || getWorkspaceDirectoryId(workspaceSavedDraft);
  const workspaceDirectoryMembers = Array.isArray(workspaceDirectory.members) ? workspaceDirectory.members : [];
  const workspaceDirectoryInvitations = Array.isArray(workspaceDirectory.invitations) ? workspaceDirectory.invitations : [];
  const workspaceDirectoryCapabilities = normalizeWorkspaceDirectoryCapabilities(workspaceDirectory.capabilities);
  const workspaceMemberMutationActive = !!(workspaceMemberAction && workspaceMemberAction.membershipId);
  const workspaceMemberMutationRuntimeAvailable = workspaceMemberMutationRuntimeReady;
  const workspaceDirectoryBusy = workspaceDirectory.loading || workspaceDirectory.loadingMoreMembers || workspaceDirectory.loadingMoreInvitations || workspaceMemberMutationActive || workspaceRemoveMemberBusy;
  const workspaceDirectoryInitialLoading = workspaceDirectory.loading && !workspaceDirectoryMembers.length && !workspaceDirectory.loaded;
  const workspaceDirectoryCanInvite = workspaceDirectoryCapabilities.canInviteMembers === true;
  const workspaceDirectoryCanManageMembers = workspaceDirectoryCapabilities.canManageMembers === true;
  const workspaceDirectoryCanChangeRoles = workspaceDirectoryCapabilities.canChangeRoles === true && workspaceMemberMutationRuntimeAvailable;
  const workspaceDirectoryCanRemoveMembers = workspaceDirectoryCapabilities.canRemoveMembers === true && workspaceMemberMutationRuntimeAvailable;
  const workspaceMemberMutationUnavailable = workspaceDirectory.loaded && !workspaceDirectory.error && workspaceDirectoryCanManageMembers && (workspaceDirectoryCapabilities.canChangeRoles === true || workspaceDirectoryCapabilities.canRemoveMembers === true) && !workspaceMemberMutationRuntimeAvailable;
  const workspaceCanGrowTeam = workspaceActionAllowed('canAddMembers');
  const workspaceInviteButtonDisabled = workspaceDirectoryBusy || !workspaceDirectory.loaded || !workspaceCanGrowTeam;
  const workspaceDirectoryAdminCount = workspaceDirectoryMembers.filter((member) => member.role === 'org:admin').length;
  const workspaceDirectoryMembersTotal = workspaceDirectory.membersPage && workspaceDirectory.membersPage.totalCount || workspaceDirectoryMembers.length;
  const workspaceDirectoryInvitationsTotal = workspaceDirectory.invitationsPage && workspaceDirectory.invitationsPage.totalCount || workspaceDirectoryInvitations.length;
  const applyAccountSecurityState = (state) => {
    if (!state || !settingsMountedRef.current) return state;
    setAccountSecurity(normalizeAccountSecurityStateForUi(state, profileDraft.email));
    return state;
  };

  const requestNativeReverification = () => {
    if (reverificationPromiseRef.current && reverificationPromiseRef.current.promise) return reverificationPromiseRef.current.promise;
    const token = Date.now();
    let resolvePromise;
    let rejectPromise;
    const promise = new Promise((resolve, reject) => {
      resolvePromise = resolve;
      rejectPromise = reject;
    });
    reverificationPromiseRef.current = { promise, resolve: resolvePromise, reject: rejectPromise };
    setReverificationRequest({ token });
    return promise;
  };

  const completeNativeReverification = () => {
    const pending = reverificationPromiseRef.current;
    reverificationPromiseRef.current = null;
    setReverificationRequest(null);
    if (pending && typeof pending.resolve === 'function') pending.resolve();
  };

  const cancelNativeReverification = () => {
    const pending = reverificationPromiseRef.current;
    reverificationPromiseRef.current = null;
    setReverificationRequest(null);
    if (pending && typeof pending.reject === 'function') pending.reject(createSettingsPublicError('Identity confirmation was canceled.', 'session_verification_cancelled'));
  };

  const runSensitiveAccountAction = (action) => {
    const attempt = (retried, continuation) => Promise.resolve().then(() => action(continuation)).catch((error) => {
      if (!isReverificationRequiredSettingsError(error) || retried) throw error;
      return requestNativeReverification().then(() => attempt(true, error && error.continuation));
    });
    return attempt(false, null);
  };

  const refreshAccountSecurityState = () => {
    const requestId = accountSecurityRequestRef.current + 1;
    accountSecurityRequestRef.current = requestId;
    setAccountSecurity((state) => ({ ...state, loading: true, email: state.email || profileDraft.email || '' }));
    setAccountSecurityError('');
    return Promise.resolve().then(() => {
      const auth = window.RankLyxAuth;
      if (!auth || typeof auth.getAccountSecurityState !== 'function') {
        const error = new Error('Account security settings are unavailable right now.');
        error.publicMessage = 'Account security settings are unavailable right now.';
        throw error;
      }
      return auth.getAccountSecurityState();
    }).then((state) => {
      if (!settingsMountedRef.current || accountSecurityRequestRef.current !== requestId) return state;
      applyAccountSecurityState(state);
      return state;
    }).catch((error) => {
      if (settingsMountedRef.current && accountSecurityRequestRef.current === requestId) {
        setAccountSecurity((state) => ({ ...state, loading: false }));
        setAccountSecurityError(getSettingsPublicErrorMessage(error, 'Account security settings are unavailable right now.'));
      }
      return null;
    });
  };

  const loadCurrentSessions = () => {
    const requestId = sessionsRequestRef.current + 1;
    sessionsRequestRef.current = requestId;
    setSessionsState((state) => ({ ...state, loading: true, error: '', notice: '', failures: [] }));
    return Promise.resolve().then(() => {
      const auth = window.RankLyxAuth;
      if (!auth || typeof auth.getCurrentUserSessions !== 'function') {
        const error = new Error('Active sessions are unavailable right now.');
        error.publicMessage = 'Active sessions are unavailable right now.';
        throw error;
      }
      return auth.getCurrentUserSessions();
    }).then((result) => {
      if (!settingsMountedRef.current || sessionsRequestRef.current !== requestId) return result;
      setSessionsState({
        loading: false,
        currentSessionId: result && result.currentSessionId || '',
        sessions: result && Array.isArray(result.sessions) ? result.sessions : [],
        error: '',
        notice: '',
        failures: []
      });
      return result;
    }).catch((error) => {
      if (settingsMountedRef.current && sessionsRequestRef.current === requestId) {
        setSessionsState((state) => ({
          ...state,
          loading: false,
          error: getSettingsPublicErrorMessage(error, 'Active sessions are unavailable right now.'),
          failures: []
        }));
      }
      return null;
    });
  };

  const submitPasswordChange = (payload) => {
    setAccountSecurityError('');
    setAccountSecurityNotice('');
    return Promise.resolve().then(() => {
      const auth = window.RankLyxAuth;
      if (!auth || typeof auth.updateCurrentUserPassword !== 'function') {
        const error = new Error('Password changes are unavailable for this account right now.');
        error.publicMessage = 'Password changes are unavailable for this account right now.';
        throw error;
      }
      return runSensitiveAccountAction(() => auth.updateCurrentUserPassword(payload));
    }).then((state) => {
      if (!settingsMountedRef.current) return state;
      setAccountSecurity(normalizeAccountSecurityStateForUi(state, profileDraft.email));
      setAccountSecurityNotice(payload && payload.hadPassword ? 'Password updated.' : 'Password added.');
      return state;
    });
  };

  const openPasswordDialog = () => {
    setAccountSecurityError('');
    setAccountSecurityNotice('');
    setPasswordDialogOpen(true);
  };

  const openMfaDialog = () => {
    if (!mfaRowCanOpen) return;
    setAccountSecurityError('');
    setAccountSecurityNotice('');
    setMfaRemoveError('');
    setMfaDialogOpen(true);
  };

  const handleMfaNotice = (message) => {
    setAccountSecurityError('');
    setAccountSecurityNotice(message);
  };

  const handleMfaError = (message) => {
    setAccountSecurityNotice('');
    setAccountSecurityError(message);
  };

  const requestMfaRemoval = () => {
    setMfaRemoveError('');
    setMfaRemoveOpen(true);
  };

  const cancelMfaRemoval = () => {
    if (mfaRemoveBusy) return;
    setMfaRemoveError('');
    setMfaRemoveOpen(false);
  };

  const confirmMfaRemoval = () => {
    if (mfaRemoveBusy) return;
    setMfaRemoveBusy(true);
    setMfaRemoveError('');
    setAccountSecurityError('');
    setAccountSecurityNotice('');
    Promise.resolve().then(() => {
      const auth = getAccountSecurityAuth();
      if (typeof auth.disableCurrentUserTOTP !== 'function') throw createSettingsPublicError('Authenticator-app security is not available for this environment yet.', 'totp_unavailable');
      return runSensitiveAccountAction(() => auth.disableCurrentUserTOTP());
    }).then((state) => {
      applyAccountSecurityState(state);
      if (!state || state.totpEnabled === true) throw createSettingsPublicError('Authenticator app removal was not confirmed. Please try again.', 'totp_disable_unconfirmed');
      setMfaRemoveOpen(false);
      setMfaDialogOpen(false);
      setAccountSecurityNotice('Authenticator app removed.');
    }).catch((removeError) => {
      setMfaRemoveError(getSettingsPublicErrorMessage(removeError, 'Authenticator app could not be removed right now.'));
    }).finally(() => setMfaRemoveBusy(false));
  };

  const openSessionsDialog = () => {
    setSessionsDialogOpen(true);
    setSessionConfirmation(null);
    loadCurrentSessions();
  };

  const requestSessionSignOut = (session) => {
    if (!session || session.isCurrent) return;
    setSessionConfirmation({ mode: 'single', sessionId: session.id, label: session.device || 'Unknown device' });
  };
  const requestSignOutAllOtherSessions = () => {
    const otherSessions = (sessionsState.sessions || []).filter((session) => !session.isCurrent);
    if (!otherSessions.length) return;
    setSessionConfirmation({ mode: 'all' });
  };

  const applySessionsResult = (result, successNotice) => {
    const failures = result && Array.isArray(result.failures) ? result.failures : [];
    const complete = failures.length === 0;
    setSessionsState({
      loading: false,
      currentSessionId: result && result.currentSessionId || '',
      sessions: result && Array.isArray(result.sessions) ? result.sessions : [],
      error: '',
      notice: complete ? successNotice : 'Some sessions could not be signed out. Review the remaining sessions and try again.',
      failures
    });
  };

  const confirmSessionAction = () => {
    if (!sessionConfirmation || sessionActionBusy) return;
    setSessionActionBusy(true);
    setSessionsState((state) => ({ ...state, error: '', notice: '', failures: [] }));
    Promise.resolve().then(() => {
      const auth = window.RankLyxAuth;
      if (!auth) {
        const error = new Error('Active sessions are unavailable right now.');
        error.publicMessage = 'Active sessions are unavailable right now.';
        throw error;
      }
      if (sessionConfirmation.mode === 'all') {
        if (typeof auth.revokeOtherCurrentUserSessions !== 'function') {
          const error = new Error('Active sessions are unavailable right now.');
          error.publicMessage = 'Active sessions are unavailable right now.';
          throw error;
        }
        return runSensitiveAccountAction((continuation) => auth.revokeOtherCurrentUserSessions(continuation));
      }
      if (typeof auth.revokeCurrentUserSession !== 'function') {
        const error = new Error('Active sessions are unavailable right now.');
        error.publicMessage = 'Active sessions are unavailable right now.';
        throw error;
      }
      return runSensitiveAccountAction(() => auth.revokeCurrentUserSession(sessionConfirmation.sessionId));
    }).then((result) => {
      if (!settingsMountedRef.current) return;
      applySessionsResult(result, sessionConfirmation.mode === 'all' ? 'Other sessions signed out.' : 'Session signed out.');
      setSessionConfirmation(null);
    }).catch((error) => {
      if (!settingsMountedRef.current) return;
      setSessionsState((state) => ({
        ...state,
        loading: false,
        error: getSettingsPublicErrorMessage(error, 'That session could not be signed out.'),
        failures: []
      }));
    }).finally(() => {
      if (settingsMountedRef.current) setSessionActionBusy(false);
    });
  };
  const resetWorkspaceMemberUi = () => {
    workspaceMemberMutationRequestRef.current += 1;
    workspaceMemberMutationBusyRef.current = false;
    setWorkspaceMemberNotice('');
    setWorkspaceMemberError('');
    setWorkspaceMemberAction({ membershipId: '', mode: '' });
    setWorkspaceRemoveMember(null);
    setWorkspaceRemoveMemberBusy(false);
    setWorkspaceRemoveMemberError('');
  };
  const resetWorkspaceInvitationUi = (options) => {
    workspaceInvitationMutationRequestRef.current += 1;
    workspaceInvitationMutationBusyRef.current = false;
    resetWorkspaceMemberUi();
    setWorkspaceInviteDialogOpen(false);
    setWorkspaceInviteForm(createWorkspaceInvitationFormState());
    setWorkspaceInvitationNotice('');
    setWorkspaceCancelInvitation(null);
    setWorkspaceCancelInvitationBusy(false);
    setWorkspaceCancelInvitationError('');
    if (options && options.returnFocus && workspaceInviteButtonRef.current) {
      window.setTimeout(() => workspaceInviteButtonRef.current && workspaceInviteButtonRef.current.focus(), 0);
    }
  };

  const handleSettingsWorkspaceSwitch = (membership) => {
    const workspaceId = getWorkspaceMembershipId(membership);
    if (!workspaceId || workspaceSettingsSwitchingId) return;
    if (workspaceId === getWorkspaceMembershipId(workspace)) {
      setWorkspaceSettingsSwitchError('');
      return;
    }
    const service = getWorkspaceSwitcherService();
    if (!service || typeof service.switchActiveWorkspace !== 'function') {
      setWorkspaceSettingsSwitchError("We couldn't switch workspaces");
      return;
    }
    workspaceDirectoryRequestRef.current += 1;
    workspaceDirectoryLoadInFlightRef.current = false;
    resetWorkspaceInvitationUi({ returnFocus: false });
    setWorkspaceSettingsSwitchingId(workspaceId);
    setWorkspaceSettingsSwitchError('');
    service.switchActiveWorkspace(window.Clerk, workspaceMemberships.state.memberships, workspaceId, { reload: true, reloadPath: '/' }).then(() => {
      setWorkspaceSettingsSwitchError('');
    }).catch(() => {
      setWorkspaceSettingsSwitchError("We couldn't switch workspaces");
    }).finally(() => {
      setWorkspaceSettingsSwitchingId('');
    });
  };
  const loadWorkspaceDirectoryPage = (mode) => {
    if (!workspaceScopeCurrent()) return Promise.resolve(null);
    const loadMode = mode === 'members' || mode === 'invitations' || mode === 'invitations-refresh' ? mode : 'initial';
    const workspaceId = workspaceDirectoryWorkspaceId;
    if (!workspaceId || workspaceDirectoryLoadInFlightRef.current) return Promise.resolve(null);
    const currentState = workspaceDirectory.workspaceId === workspaceId ? workspaceDirectory : createWorkspaceDirectoryState(workspaceId);
    const memberOffset = loadMode === 'members' && currentState.membersPage ? currentState.membersPage.nextOffset : 0;
    const invitationOffset = loadMode === 'invitations' && currentState.invitationsPage ? currentState.invitationsPage.nextOffset : 0;
    const requestId = workspaceDirectoryRequestRef.current + 1;
    workspaceDirectoryRequestRef.current = requestId;
    workspaceDirectoryLoadInFlightRef.current = true;
    setWorkspaceDirectory((state) => {
      const base = state.workspaceId === workspaceId ? state : createWorkspaceDirectoryState(workspaceId);
      return {
        ...base,
        workspaceId,
        error: '',
        loading: loadMode === 'initial',
        loadingMoreMembers: loadMode === 'members',
        loadingMoreInvitations: loadMode === 'invitations' || loadMode === 'invitations-refresh'
      };
    });
    return Promise.resolve().then(() => {
      const auth = window.RankLyxAuth;
      if (!auth || typeof auth.authenticatedFetch !== 'function') {
        throw createSettingsPublicError('Workspace members could not be loaded right now.', 'workspace_members_unavailable');
      }
      return auth.authenticatedFetch(buildWorkspaceMembersDirectoryUrl({
        memberOffset,
        invitationOffset,
        limit: WORKSPACE_DIRECTORY_PAGE_LIMIT
      }), { method: 'GET' });
    }).then(parseWorkspaceMembersDirectoryResponse).then((payload) => {
      if (!settingsMountedRef.current || workspaceDirectoryRequestRef.current !== requestId) return payload;
      const normalized = normalizeWorkspaceDirectoryPayloadForUi(payload, WORKSPACE_DIRECTORY_PAGE_LIMIT);
      if (normalized.workspaceId && normalized.workspaceId !== workspaceId) return payload;
      if (loadMode === 'initial' && !normalized.members.length) {
        throw createSettingsPublicError('Workspace members could not be loaded right now.', 'workspace_members_empty');
      }
      setWorkspaceDirectory((state) => {
        if (state.workspaceId !== workspaceId || workspaceDirectoryRequestRef.current !== requestId) return state;
        if (loadMode === 'members') {
          return {
            ...state,
            ...normalized,
            workspaceId,
            members: mergeWorkspaceDirectoryItems(state.members, normalized.members, 'membershipId'),
            invitations: state.invitations,
            invitationsPage: state.invitationsPage,
            loading: false,
            loadingMoreMembers: false,
            loadingMoreInvitations: false,
            error: ''
          };
        }
        if (loadMode === 'invitations-refresh') {
          return {
            ...state,
            ...normalized,
            workspaceId,
            members: state.members,
            membersPage: state.membersPage,
            invitations: normalized.invitations,
            invitationsPage: normalized.invitationsPage,
            loading: false,
            loadingMoreMembers: false,
            loadingMoreInvitations: false,
            error: ''
          };
        }
        if (loadMode === 'invitations') {
          return {
            ...state,
            ...normalized,
            workspaceId,
            members: state.members,
            membersPage: state.membersPage,
            invitations: mergeWorkspaceDirectoryItems(state.invitations, normalized.invitations, 'invitationId'),
            loading: false,
            loadingMoreMembers: false,
            loadingMoreInvitations: false,
            error: ''
          };
        }
        return { ...normalized, workspaceId: normalized.workspaceId || workspaceId };
      });
      return payload;
    }).catch((error) => {
      if (settingsMountedRef.current && workspaceDirectoryRequestRef.current === requestId) {
        setWorkspaceDirectory((state) => ({
          ...state,
          workspaceId,
          loading: false,
          loadingMoreMembers: false,
          loadingMoreInvitations: false,
          error: getSettingsPublicErrorMessage(error, 'Workspace members could not be loaded right now.')
        }));
      }
      return null;
    }).finally(() => {
      if (workspaceDirectoryRequestRef.current === requestId) {
        workspaceDirectoryLoadInFlightRef.current = false;
      }
    });
  };

  const retryWorkspaceDirectoryLoad = () => {
    if (workspaceDirectoryBusy || workspaceDirectoryLoadInFlightRef.current) return;
    setWorkspaceDirectory((state) => ({ ...state, loaded: false, loading: false, error: '' }));
    setWorkspaceDirectoryRetryToken((token) => token + 1);
  };

  const refreshWorkspaceInvitationsAfterMutation = () => loadWorkspaceDirectoryPage('invitations-refresh');
  const refreshWorkspaceMembersAfterMutation = () => loadWorkspaceDirectoryPage('initial');

  const openWorkspaceInviteDialog = () => {
    if (!workspaceActionAllowed('canAddMembers')) return;
    if (!workspaceDirectoryCanInvite || workspaceInviteButtonDisabled) return;
    setWorkspaceMemberNotice('');
    setWorkspaceMemberError('');
    setWorkspaceInvitationNotice('');
    setWorkspaceCancelInvitation(null);
    setWorkspaceCancelInvitationError('');
    setWorkspaceInviteForm(createWorkspaceInvitationFormState());
    setWorkspaceInviteDialogOpen(true);
  };

  const closeWorkspaceInviteDialog = () => {
    if (workspaceInviteForm.submitting) return;
    setWorkspaceInviteDialogOpen(false);
    setWorkspaceInviteForm(createWorkspaceInvitationFormState());
    if (workspaceInviteButtonRef.current) {
      window.setTimeout(() => workspaceInviteButtonRef.current && workspaceInviteButtonRef.current.focus(), 0);
    }
  };

  const updateWorkspaceInviteEmail = (value) => {
    if (!workspaceCanGrowTeam || !workspaceActionAllowed('canAddMembers')) return;
    setWorkspaceInviteForm((state) => ({ ...state, emailAddress: value, issuanceRequestId: '', emailError: '', error: '' }));
  };

  const updateWorkspaceInviteRole = (value) => {
    if (!workspaceCanGrowTeam || !workspaceActionAllowed('canAddMembers')) return;
    const validRole = value === 'org:admin' ? 'org:admin' : WORKSPACE_INVITATION_DEFAULT_ROLE;
    setWorkspaceInviteForm((state) => ({ ...state, role: validRole, issuanceRequestId: '', error: '' }));
  };

  const submitWorkspaceInvitation = (event) => {
    if (event && typeof event.preventDefault === 'function') event.preventDefault();
    if (!workspaceDirectoryCanInvite || !workspaceActionAllowed('canAddMembers')) return;
    if (workspaceInvitationMutationBusyRef.current || workspaceInviteForm.submitting) return;
    const validated = validateWorkspaceInvitationEmailInput(workspaceInviteForm.emailAddress);
    if (validated.error) {
      setWorkspaceInviteForm((state) => ({ ...state, emailAddress: validated.emailAddress, emailError: validated.error, error: '' }));
      return;
    }
    const role = workspaceInviteForm.role === 'org:admin' ? 'org:admin' : WORKSPACE_INVITATION_DEFAULT_ROLE;
    const workspaceId = workspaceDirectoryWorkspaceId;
    const issuanceRequestId = workspaceInviteForm.issuanceRequestId || window.crypto.randomUUID();
    const requestId = workspaceInvitationMutationRequestRef.current + 1;
    workspaceInvitationMutationRequestRef.current = requestId;
    workspaceInvitationMutationBusyRef.current = true;
    setWorkspaceInviteForm((state) => ({ ...state, emailAddress: validated.emailAddress, role, issuanceRequestId, emailError: '', error: '', submitting: true }));
    Promise.resolve().then(() => {
      if (workspaceInvitationMutationRequestRef.current !== requestId || !workspaceActionAllowed('canAddMembers')) throw createSettingsPublicError('Workspace invitations are unavailable right now.', 'workspace_access_changed');
      const auth = window.RankLyxAuth;
      if (!auth || typeof auth.authenticatedFetch !== 'function') {
        throw createSettingsPublicError('Workspace invitations are unavailable right now.', 'workspace_invitation_unavailable');
      }
      return auth.authenticatedFetch(buildWorkspaceInvitationsUrl(), {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ emailAddress: validated.emailAddress, role, requestId: issuanceRequestId })
      });
    }).then(parseWorkspaceInvitationMutationResponse).then(() => {
      if (!settingsMountedRef.current || workspaceInvitationMutationRequestRef.current !== requestId || workspaceDirectoryWorkspaceId !== workspaceId) return null;
      workspaceInvitationMutationBusyRef.current = false;
      setWorkspaceInviteDialogOpen(false);
      setWorkspaceInviteForm(createWorkspaceInvitationFormState());
      setWorkspaceInvitationNotice('Invitation sent.');
      if (workspaceInviteButtonRef.current) {
        window.setTimeout(() => workspaceInviteButtonRef.current && workspaceInviteButtonRef.current.focus(), 0);
      }
      return refreshWorkspaceInvitationsAfterMutation();
    }).catch((error) => {
      if (!settingsMountedRef.current || workspaceInvitationMutationRequestRef.current !== requestId) return;
      const message = getSettingsPublicErrorMessage(error, 'Invitation could not be sent.');
      setWorkspaceInviteForm((state) => ({
        ...state,
        submitting: false,
        emailError: error && error.code === 'workspace_invitation_email_invalid' ? message : state.emailError,
        error: error && error.code === 'workspace_invitation_email_invalid' ? '' : message
      }));
    }).finally(() => {
      if (workspaceInvitationMutationRequestRef.current === requestId) {
        workspaceInvitationMutationBusyRef.current = false;
      }
    });
  };

  const requestCancelWorkspaceInvitation = (invitation) => {
    if (!workspaceScopeCurrent() || !workspaceAdmin) return;
    if (!workspaceDirectoryCanInvite || workspaceDirectoryBusy || workspaceCancelInvitationBusy || !invitation || !invitation.invitationId) return;
    setWorkspaceInvitationNotice('');
    setWorkspaceCancelInvitation(invitation);
    setWorkspaceCancelInvitationError('');
  };

  const closeWorkspaceCancelInvitation = () => {
    if (workspaceCancelInvitationBusy) return;
    setWorkspaceCancelInvitation(null);
    setWorkspaceCancelInvitationError('');
  };

  const confirmWorkspaceCancelInvitation = () => {
    if (!workspaceScopeCurrent() || !workspaceAdmin || !workspaceDirectoryCanInvite) return;
    if (workspaceInvitationMutationBusyRef.current || workspaceCancelInvitationBusy || !workspaceCancelInvitation || !workspaceCancelInvitation.invitationId) return;
    const invitationId = workspaceCancelInvitation.invitationId;
    const workspaceId = workspaceDirectoryWorkspaceId;
    const requestId = workspaceInvitationMutationRequestRef.current + 1;
    workspaceInvitationMutationRequestRef.current = requestId;
    workspaceInvitationMutationBusyRef.current = true;
    setWorkspaceCancelInvitationBusy(true);
    setWorkspaceCancelInvitationError('');
    Promise.resolve().then(() => {
      if (!workspaceScopeCurrent() || workspaceInvitationMutationRequestRef.current !== requestId) throw createSettingsPublicError('Workspace changed. Try again.', 'workspace_scope_changed');
      const auth = window.RankLyxAuth;
      if (!auth || typeof auth.authenticatedFetch !== 'function') {
        throw createSettingsPublicError('Workspace invitations are unavailable right now.', 'workspace_invitation_unavailable');
      }
      return auth.authenticatedFetch(buildWorkspaceInvitationsUrl(), {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ invitationId })
      });
    }).then(parseWorkspaceInvitationMutationResponse).then(() => {
      if (!settingsMountedRef.current || workspaceInvitationMutationRequestRef.current !== requestId || workspaceDirectoryWorkspaceId !== workspaceId) return null;
      workspaceInvitationMutationBusyRef.current = false;
      setWorkspaceCancelInvitation(null);
      setWorkspaceCancelInvitationError('');
      setWorkspaceInvitationNotice('Invitation canceled.');
      return refreshWorkspaceInvitationsAfterMutation();
    }).catch((error) => {
      if (!settingsMountedRef.current || workspaceInvitationMutationRequestRef.current !== requestId) return;
      setWorkspaceCancelInvitationError(getSettingsPublicErrorMessage(error, 'Invitation could not be canceled.'));
      if (error && (error.code === 'workspace_invitation_not_found' || error.code === 'workspace_invitation_not_pending')) {
        refreshWorkspaceInvitationsAfterMutation();
      }
    }).finally(() => {
      if (workspaceInvitationMutationRequestRef.current === requestId) {
        workspaceInvitationMutationBusyRef.current = false;
        setWorkspaceCancelInvitationBusy(false);
      }
    });
  };
  const updateWorkspaceMemberRole = (member, role) => {
    if (!workspaceScopeCurrent() || !workspaceAdmin) return;
    if (workspaceDirectoryCapabilities.canChangeRoles !== true || workspaceMemberMutationBusyRef.current || workspaceDirectoryBusy) return;
    const roleChange = getWorkspaceMemberRoleChange(member, role);
    if (!roleChange.shouldSubmit) return;
    const nextRole = roleChange.nextRole;
    if (nextRole === 'org:admin' && !workspaceActionAllowed('canAddMembers')) return;
    if (member.role === 'org:admin' && nextRole === 'org:member' && workspaceDirectoryAdminCount <= 1) {
      setWorkspaceMemberNotice('');
      setWorkspaceMemberError('Every Workspace must have at least one Administrator.');
      return;
    }
    const membershipId = member.membershipId;
    const workspaceId = workspaceDirectoryWorkspaceId;
    const requestId = workspaceMemberMutationRequestRef.current + 1;
    workspaceMemberMutationRequestRef.current = requestId;
    workspaceMemberMutationBusyRef.current = true;
    setWorkspaceMemberAction({ membershipId, mode: 'role' });
    setWorkspaceMemberNotice('');
    setWorkspaceMemberError('');
    setWorkspaceInvitationNotice('');
    Promise.resolve().then(() => {
      if (!workspaceScopeCurrent() || workspaceMemberMutationRequestRef.current !== requestId) throw createSettingsPublicError('Workspace changed. Try again.', 'workspace_scope_changed');
      if (nextRole === 'org:admin' && !workspaceActionAllowed('canAddMembers')) throw createSettingsPublicError('Workspace role changes are unavailable right now.', 'workspace_access_changed');
      const auth = getWorkspaceMemberMutationAuth();
      if (!auth) {
        setWorkspaceMemberMutationRuntimeReady(false);
        throw createSettingsPublicError('Workspace member changes are unavailable right now.', 'workspace_membership_runtime_unavailable');
      }
      setWorkspaceMemberMutationRuntimeReady(true);
      return auth.authenticatedFetch(buildWorkspaceMemberMutationUrl(), buildWorkspaceMemberRoleMutationOptions(membershipId, nextRole));
    }).then(parseWorkspaceMemberMutationResponse).then(() => {
      if (!settingsMountedRef.current || workspaceMemberMutationRequestRef.current !== requestId || workspaceDirectoryWorkspaceId !== workspaceId) return null;
      workspaceMemberMutationBusyRef.current = false;
      setWorkspaceMemberAction({ membershipId: '', mode: '' });
      setWorkspaceMemberNotice('Workspace member role updated.');
      return refreshWorkspaceMembersAfterMutation();
    }).catch((error) => {
      if (!settingsMountedRef.current || workspaceMemberMutationRequestRef.current !== requestId) return;
      setWorkspaceMemberError(getSettingsPublicErrorMessage(error, 'Workspace member could not be updated.'));
      if (error && (error.code === 'workspace_membership_required' || error.code === 'final_workspace_administrator')) {
        refreshWorkspaceMembersAfterMutation();
      }
    }).finally(() => {
      if (workspaceMemberMutationRequestRef.current === requestId) {
        workspaceMemberMutationBusyRef.current = false;
        setWorkspaceMemberAction({ membershipId: '', mode: '' });
      }
    });
  };

  const requestRemoveWorkspaceMember = (member) => {
    if (!workspaceScopeCurrent() || !workspaceAdmin) return;
    if (!workspaceDirectoryCanRemoveMembers || workspaceMemberMutationBusyRef.current || workspaceDirectoryBusy || !member || !member.membershipId || member.isCurrentUser) return;
    if (!isWorkspaceMemberRoleSupported(member.role)) return;
    if (member.role === 'org:admin' && workspaceDirectoryAdminCount <= 1) {
      setWorkspaceMemberNotice('');
      setWorkspaceMemberError('Every Workspace must have at least one Administrator.');
      return;
    }
    setWorkspaceInvitationNotice('');
    setWorkspaceMemberNotice('');
    setWorkspaceMemberError('');
    setWorkspaceRemoveMember(member);
    setWorkspaceRemoveMemberError('');
  };

  const closeWorkspaceRemoveMember = () => {
    if (workspaceRemoveMemberBusy) return;
    setWorkspaceRemoveMember(null);
    setWorkspaceRemoveMemberError('');
  };

  const confirmWorkspaceRemoveMember = () => {
    if (!workspaceScopeCurrent() || !workspaceAdmin || !workspaceDirectoryCanRemoveMembers) return;
    if (workspaceRemoveMember && (workspaceRemoveMember.isCurrentUser || (workspaceRemoveMember.role === 'org:admin' && workspaceDirectoryAdminCount <= 1))) return;
    if (workspaceMemberMutationBusyRef.current || workspaceRemoveMemberBusy || !workspaceRemoveMember || !workspaceRemoveMember.membershipId) return;
    const membershipId = workspaceRemoveMember.membershipId;
    const workspaceId = workspaceDirectoryWorkspaceId;
    const requestId = workspaceMemberMutationRequestRef.current + 1;
    workspaceMemberMutationRequestRef.current = requestId;
    workspaceMemberMutationBusyRef.current = true;
    setWorkspaceMemberAction({ membershipId, mode: 'remove' });
    setWorkspaceRemoveMemberBusy(true);
    setWorkspaceRemoveMemberError('');
    Promise.resolve().then(() => {
      if (!workspaceScopeCurrent() || workspaceMemberMutationRequestRef.current !== requestId) throw createSettingsPublicError('Workspace changed. Try again.', 'workspace_scope_changed');
      const auth = getWorkspaceMemberMutationAuth();
      if (!auth) {
        setWorkspaceMemberMutationRuntimeReady(false);
        throw createSettingsPublicError('Workspace member changes are unavailable right now.', 'workspace_membership_runtime_unavailable');
      }
      setWorkspaceMemberMutationRuntimeReady(true);
      return auth.authenticatedFetch(buildWorkspaceMemberMutationUrl(), {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ membershipId })
      });
    }).then(parseWorkspaceMemberMutationResponse).then(() => {
      if (!settingsMountedRef.current || workspaceMemberMutationRequestRef.current !== requestId || workspaceDirectoryWorkspaceId !== workspaceId) return null;
      workspaceMemberMutationBusyRef.current = false;
      setWorkspaceRemoveMember(null);
      setWorkspaceRemoveMemberError('');
      setWorkspaceMemberAction({ membershipId: '', mode: '' });
      setWorkspaceMemberNotice('Workspace member removed.');
      return refreshWorkspaceMembersAfterMutation();
    }).catch((error) => {
      if (!settingsMountedRef.current || workspaceMemberMutationRequestRef.current !== requestId) return;
      setWorkspaceRemoveMemberError(getSettingsPublicErrorMessage(error, 'Workspace member could not be removed.'));
      if (error && (error.code === 'workspace_membership_required' || error.code === 'final_workspace_administrator')) {
        refreshWorkspaceMembersAfterMutation();
      }
    }).finally(() => {
      if (workspaceMemberMutationRequestRef.current === requestId) {
        workspaceMemberMutationBusyRef.current = false;
        setWorkspaceRemoveMemberBusy(false);
        setWorkspaceMemberAction({ membershipId: '', mode: '' });
      }
    });
  };
  useEffect(() => {
    setProfileDraft(user || loadProfileSettings());
    resetPendingAvatarState();
    setProfileError('');
    setAccountSecurity((state) => ({ ...state, email: user && user.email || '', loaded: false }));
    setAccountSecurityError('');
    setAccountSecurityNotice('');
  }, [user]);
  useEffect(() => {
    const requestedId = requestedSection && requestedSection.section;
    if (!requestedId) return;
    const nextId = normalizeSettingsSectionId(requestedId, settingsSections);
    setSelected(nextId);
    setSaved('');
  }, [requestedSection && requestedSection.token, workspaceAdmin]);
  useEffect(() => {
    if (selected !== requestedSectionId) setSelected(requestedSectionId);
  }, [selected, requestedSectionId]);
  useEffect(() => {
    const nextWorkspace = normalizeWorkspaceSettings(workspace || loadWorkspaceSettings());
    const nextWorkspaceId = getWorkspaceDirectoryId(nextWorkspace);
    if (workspaceDirectory.workspaceId !== nextWorkspaceId) resetWorkspaceInvitationUi({ returnFocus: false });
    setWorkspaceSavedDraft(nextWorkspace);
    setWorkspaceDirectory((state) => {
      if (state.workspaceId === nextWorkspaceId) return state;
      workspaceDirectoryRequestRef.current += 1;
      workspaceDirectoryLoadInFlightRef.current = false;
      return createWorkspaceDirectoryState(nextWorkspaceId);
    });
    setWorkspaceDirectoryRetryToken(0);
    if (!workspaceDirtyRef.current) {
      setWorkspaceDraft(nextWorkspace);
      resetPendingWorkspaceLogoState();
      setWorkspaceError('');
    }
  }, [workspace]);
  useEffect(() => {
    if (!workspaceScopeActiveRef.current && workspaceAccess.workspaceId === workspaceScopeId && workspaceAccess.status !== 'loading') {
      workspaceScopeActiveRef.current = true;
      setWorkspaceLoadRetryToken((token) => token + 1);
      setWorkspaceDirectoryRetryToken((token) => token + 1);
    }
  }, [workspaceAccess.workspaceId, workspaceAccess.status]);
  useEffect(() => {
    const handleWorkspaceSwitching = () => {
      workspaceScopeActiveRef.current = false;
      workspaceLoadRequestRef.current += 1;
      workspaceLoadInFlightRef.current = false;
      workspaceDirtyRef.current = false;
      setWorkspaceLoaded(false);
      setWorkspaceLoadFailed(false);
      setLoadingWorkspace(false);
      setSavingWorkspace(false);
      setWorkspaceDraft(normalizeWorkspaceSettings({}));
      setWorkspaceSavedDraft(normalizeWorkspaceSettings({}));
      setWorkspaceDirectory(createWorkspaceDirectoryState(''));
      resetPendingWorkspaceLogoState();
      workspaceDirectoryRequestRef.current += 1;
      workspaceDirectoryLoadInFlightRef.current = false;
      resetWorkspaceInvitationUi({ returnFocus: false });
      setWorkspaceSettingsSwitchError('');
      const checkoutCoordinator = checkoutCoordinatorRef.current;
      if (checkoutCoordinator) checkoutCoordinator.cancel();
      const checkoutReturnCoordinator = checkoutReturnCoordinatorRef.current;
      if (checkoutReturnCoordinator) checkoutReturnCoordinator.cancel();
      setCheckoutReturnState({ status: 'idle', workspaceId: '', errorCode: '' });
      setCheckoutBillingInterval('monthly');
      setCheckoutState({ status: 'idle', workspaceId: '', planKey: '', billingInterval: 'monthly', message: '' });
      const upgradeCoordinator = upgradeCoordinatorRef.current;
      if (upgradeCoordinator) upgradeCoordinator.cancel();
      setUpgradeConfirmation(null);
      const coordinator = subscriptionMutationCoordinatorRef.current;
      if (coordinator) coordinator.cancel();
      setSubscriptionConfirmation(null);
      setSubscriptionMutationState({ status: 'idle', workspaceId: '', desiredCancellationScheduled: null, error: '' });
    };
    window.addEventListener('ranklyx:workspace-switching', handleWorkspaceSwitching);
    return () => window.removeEventListener('ranklyx:workspace-switching', handleWorkspaceSwitching);
  }, []);
  useEffect(() => {
    const refreshWorkspaceMemberMutationRuntimeReady = () => {
      const available = isWorkspaceMemberMutationRuntimeAvailable();
      setWorkspaceMemberMutationRuntimeReady((current) => current === available ? current : available);
      return available;
    };
    if (refreshWorkspaceMemberMutationRuntimeReady()) return undefined;
    const intervalId = window.setInterval(refreshWorkspaceMemberMutationRuntimeReady, 100);
    return () => window.clearInterval(intervalId);
  }, []);

  useEffect(() => {
    if (selected !== 'workspace' || workspaceLoaded || workspaceLoadFailed || workspaceLoadInFlightRef.current) return undefined;
    if (!workspaceScopeCurrent()) return undefined;
    const requestId = workspaceLoadRequestRef.current + 1;
    workspaceLoadRequestRef.current = requestId;
    workspaceLoadInFlightRef.current = true;
    setLoadingWorkspace(true);
    clearWorkspaceSaveFeedback();
    setWorkspaceError('');
    setWorkspaceLoadFailed(false);
    Promise.resolve().then(() => {
      const service = window.RankLyxAccountWorkspace;
      if (!service || typeof service.getWorkspaceSettings !== 'function') {
        const error = new Error('Your workspace settings could not be loaded.');
        error.publicMessage = 'Your workspace settings could not be loaded.';
        throw error;
      }
      return service.getWorkspaceSettings(window.Clerk);
    }).then((loadedWorkspace) => {
      if (!settingsMountedRef.current || workspaceLoadRequestRef.current !== requestId) return;
      const nextWorkspace = normalizeWorkspaceSettings(loadedWorkspace);
      const current = window.currentWorkspace || {};
      window.currentWorkspace = { ...current, ...nextWorkspace };
      setWorkspaceSavedDraft(nextWorkspace);
      if (!workspaceDirtyRef.current) setWorkspaceDraft(nextWorkspace);
      if (onSaveWorkspace) onSaveWorkspace(nextWorkspace);
      setWorkspaceLoadFailed(false);
      setWorkspaceLoaded(true);
    }).catch((error) => {
      if (!settingsMountedRef.current || workspaceLoadRequestRef.current !== requestId) return;
      setWorkspaceError(error && error.publicMessage ? error.publicMessage : 'Your workspace settings could not be loaded.');
      setWorkspaceLoadFailed(true);
      setWorkspaceLoaded(false);
    }).finally(() => {
      if (workspaceLoadRequestRef.current === requestId) {
        workspaceLoadInFlightRef.current = false;
        if (settingsMountedRef.current) setLoadingWorkspace(false);
      }
    });
    return undefined;
  }, [selected, workspaceLoaded, workspaceLoadFailed, workspaceLoadRetryToken, onSaveWorkspace, workspaceAccess.status]);

  useEffect(() => {
    if (selected !== 'workspace') return undefined;
    const scopeCurrent = workspaceScopeCurrent();
    if (!scopeCurrent) return undefined;
    const workspaceId = workspaceDirectoryWorkspaceId;
    if (!workspaceId) {
      setWorkspaceDirectory((state) => state.workspaceId ? createWorkspaceDirectoryState('') : state);
      return undefined;
    }
    if (workspaceDirectory.workspaceId !== workspaceId) {
      workspaceDirectoryRequestRef.current += 1;
      workspaceDirectoryLoadInFlightRef.current = false;
      resetWorkspaceInvitationUi({ returnFocus: false });
      setWorkspaceDirectory(createWorkspaceDirectoryState(workspaceId));
      return undefined;
    }
    if (workspaceDirectory.loaded || workspaceDirectory.error || workspaceDirectory.loading || workspaceDirectory.loadingMoreMembers || workspaceDirectory.loadingMoreInvitations || workspaceDirectoryLoadInFlightRef.current) return undefined;
    loadWorkspaceDirectoryPage('initial');
    return undefined;
  }, [selected, workspaceDirectoryWorkspaceId, workspaceDirectory.workspaceId, workspaceDirectory.loaded, workspaceDirectory.error, workspaceDirectory.loading, workspaceDirectory.loadingMoreMembers, workspaceDirectory.loadingMoreInvitations, workspaceDirectoryRetryToken]);

  useEffect(() => {
    if (selectedSectionId !== 'profile') return undefined;
    refreshAccountSecurityState();
    return undefined;
  }, [selectedSectionId, user]);

  useEffect(() => {
    settingsMountedRef.current = true;
    return () => {
      settingsMountedRef.current = false;
      if (pendingAvatarUrlRef.current && window.URL && typeof window.URL.revokeObjectURL === 'function') {
        window.URL.revokeObjectURL(pendingAvatarUrlRef.current);
      }
      if (pendingWorkspaceLogoUrlRef.current && window.URL && typeof window.URL.revokeObjectURL === 'function') {
        window.URL.revokeObjectURL(pendingWorkspaceLogoUrlRef.current);
      }
      clearProfileSaveFeedbackTimer();
      clearWorkspaceSaveFeedbackTimer();
      const subscriptionCoordinator = subscriptionMutationCoordinatorRef.current;
      if (subscriptionCoordinator) subscriptionCoordinator.cancel();
      const checkoutCoordinator = checkoutCoordinatorRef.current;
      if (checkoutCoordinator) checkoutCoordinator.cancel();
      const upgradeCoordinator = upgradeCoordinatorRef.current;
      if (upgradeCoordinator) upgradeCoordinator.cancel();
      const checkoutReturnCoordinator = checkoutReturnCoordinatorRef.current;
      if (checkoutReturnCoordinator) checkoutReturnCoordinator.cancel();
      if (reverificationPromiseRef.current && typeof reverificationPromiseRef.current.reject === 'function') {
        reverificationPromiseRef.current.reject(createSettingsPublicError('Identity confirmation was canceled.', 'session_verification_cancelled'));
        reverificationPromiseRef.current = null;
      }
    };
  }, []);

  const openAvatarPicker = () => {
    if (avatarInputRef.current) avatarInputRef.current.click();
  };

  const applyProfileResult = (profile) => {
    const source = profile || {};
    const current = window.currentUser || {};
    const firstName = source.firstName || '';
    const lastName = source.lastName || '';
    const fullName = source.fullName || source.displayName || [firstName, lastName].filter(Boolean).join(' ') || current.fullName || 'Account';
    const imageUrl = source.imageUrl || source.avatarDataUrl || '';
    const next = {
      ...current,
      ...source,
      id: source.id || source.userId || current.id || '',
      userId: source.userId || source.id || current.userId || current.id || '',
      firstName,
      lastName,
      fullName,
      displayName: source.displayName || fullName,
      name: firstName || fullName,
      email: source.email || current.email || '',
      avatarDataUrl: imageUrl,
      imageUrl,
      hasImage: !!source.hasImage
    };
    window.currentUser = next;
    setProfileDraft(next);
    if (onSaveProfile) onSaveProfile(next);
    return next;
  };

  const saveProfile = () => {
    if (!profileChanged || savingProfile) return;
    const fallbackMessage = 'Your profile could not be saved.';
    clearProfileSaveFeedback();
    setProfileError('');
    setSaved('');
    setSavingProfile(true);
    Promise.resolve().then(() => {
      const service = window.RankLyxAccountWorkspace;
      if (!service || typeof service.updateProfileSettings !== 'function') {
        const error = new Error(fallbackMessage);
        error.publicMessage = fallbackMessage;
        throw error;
      }
      return service.updateProfileSettings(window.Clerk, {
        firstName: String(profileDraft.firstName || '').trim(),
        lastName: String(profileDraft.lastName || '').trim(),
        profileImageFile: pendingAvatarFile || null,
        removeProfileImage: pendingAvatarRemoval
      });
    }).then((result) => {
      const nextProfile = result && result.profile ? result.profile : profileDraft;
      clearPendingAvatarPreview();
      setPendingAvatarRemoval(false);
      applyProfileResult(nextProfile);
      showProfileSavedFeedback();
    }).catch((error) => {
      clearProfileSaveFeedback();
      if (error && error.partial && error.profile) {
        clearPendingAvatarPreview();
        setPendingAvatarRemoval(false);
        applyProfileResult(error.profile);
      }
      setProfileError(error && error.publicMessage ? error.publicMessage : fallbackMessage);
    }).finally(() => {
      setSavingProfile(false);
    });
  };

  const handleAvatarFile = (event) => {
    const file = event.target.files && event.target.files[0];
    event.target.value = '';
    if (!file) return;
    clearProfileSaveFeedback();
    if (!/^image\/(png|jpe?g|webp)$/i.test(file.type)) {
      setProfileError('Please choose a PNG, JPG, JPEG, or WebP image.');
      return;
    }
    if (!window.URL || typeof window.URL.createObjectURL !== 'function') {
      setProfileError('The image could not be prepared. Please try another file.');
      return;
    }
    const previewUrl = window.URL.createObjectURL(file);
    clearPendingAvatarPreview();
    pendingAvatarUrlRef.current = previewUrl;
    setPendingAvatarUrl(previewUrl);
    setPendingAvatarFile(file);
    setPendingAvatarRemoval(false);
    setProfileError('');
    setSaved('');
  };

  const removeAvatar = () => {
    if (!canRemoveAvatar) return;
    clearProfileSaveFeedback();
    clearPendingAvatarPreview();
    setPendingAvatarRemoval(true);
    setProfileError('');
    setSaved('');
  };

  const handleSettingsTabKeyDown = (event, index) => {
    const key = event.key;
    if (![ 'ArrowRight', 'ArrowLeft', 'Home', 'End' ].includes(key)) return;
    event.preventDefault();
    const lastIndex = settingsSections.length - 1;
    const nextIndex = key === 'Home' ? 0 : key === 'End' ? lastIndex : key === 'ArrowRight' ? (index + 1) % settingsSections.length : (index - 1 + settingsSections.length) % settingsSections.length;
    const nextSection = settingsSections[nextIndex];
    if (!nextSection) return;
    setSelected(nextSection.id);
    setSaved('');
    window.requestAnimationFrame(() => { const nextButton = document.getElementById('settings-tab-' + nextSection.id); if (nextButton) nextButton.focus(); });
  };



  const applyWorkspaceResult = (workspaceResult) => {
    const nextWorkspace = normalizeWorkspaceSettings({ ...(window.currentWorkspace || {}), ...(workspaceResult || {}) });
    window.currentWorkspace = { ...(window.currentWorkspace || {}), ...nextWorkspace };
    setWorkspaceDraft(nextWorkspace);
    setWorkspaceSavedDraft(nextWorkspace);
    workspaceDirtyRef.current = false;
    if (onSaveWorkspace) onSaveWorkspace(nextWorkspace);
    return nextWorkspace;
  };

  const applyWorkspacePartialResult = (workspaceResult, options = {}) => {
    const partialWorkspace = normalizeWorkspaceSettings({ ...(window.currentWorkspace || {}), ...(workspaceResult || {}) });
    window.currentWorkspace = { ...(window.currentWorkspace || {}), ...partialWorkspace };
    setWorkspaceSavedDraft(partialWorkspace);
    if (onSaveWorkspace) onSaveWorkspace(partialWorkspace);
    setWorkspaceDraft((draft) => {
      const keepPendingLogo = !!options.preservePendingLogo;
      return normalizeWorkspaceSettings({
        ...draft,
        id: partialWorkspace.id || draft.id,
        organizationId: partialWorkspace.organizationId || partialWorkspace.id || draft.organizationId,
        role: partialWorkspace.role || draft.role,
        membersCount: partialWorkspace.membersCount == null ? draft.membersCount : partialWorkspace.membersCount,
        imageUrl: keepPendingLogo ? draft.imageUrl : partialWorkspace.imageUrl,
        logoDataUrl: keepPendingLogo ? draft.logoDataUrl : partialWorkspace.logoDataUrl,
        hasImage: keepPendingLogo ? draft.hasImage : partialWorkspace.hasImage
      });
    });
    return partialWorkspace;
  };

  const saveWorkspace = () => {
    if (!workspaceActionAllowed('canMutateWorkspaceContent')) return;
    if (workspaceSaveDisabled) return;
    const requestId = workspaceLoadRequestRef.current;
    const websiteValidation = validateOptionalWebsiteInput(workspaceDraftWebsite);
    if (!websiteValidation.valid) {
      clearWorkspaceSaveFeedback();
      setWorkspaceError(websiteValidation.message);
      setSaved('');
      return;
    }
    const fallbackMessage = 'Your workspace settings could not be saved.';
    clearWorkspaceSaveFeedback();
    setWorkspaceError('');
    setSaved('');
    setSavingWorkspace(true);
    Promise.resolve().then(() => {
      if (workspaceLoadRequestRef.current !== requestId || !workspaceActionAllowed('canMutateWorkspaceContent')) throw createSettingsPublicError('Workspace editing is unavailable right now.', 'workspace_access_changed');
      const service = window.RankLyxAccountWorkspace;
      if (!service || typeof service.updateWorkspaceSettings !== 'function') {
        const error = new Error(fallbackMessage);
        error.publicMessage = fallbackMessage;
        throw error;
      }
      return service.updateWorkspaceSettings(window.Clerk, {
        name: workspaceDraftName,
        websiteUrl: websiteValidation.value,
        workspaceLogoFile: pendingWorkspaceLogoFile || null,
        removeWorkspaceLogo: pendingWorkspaceLogoRemoval
      });
    }).then((result) => {
      if (!workspaceScopeCurrent() || workspaceLoadRequestRef.current !== requestId) return;
      clearPendingWorkspaceLogoPreview();
      setPendingWorkspaceLogoRemoval(false);
      applyWorkspaceResult(result && result.workspace ? result.workspace : workspaceDraft);
      setWorkspaceLoaded(true);
      showWorkspaceSavedFeedback();
    }).catch((error) => {
      if (!workspaceScopeCurrent() || workspaceLoadRequestRef.current !== requestId) return;
      clearWorkspaceSaveFeedback();
      if (error && error.partial && error.workspace) {
        const logoFailed = error.code === 'workspace_logo_update_failed' || error.code === 'workspace_logo_update_unavailable';
        if (!logoFailed) {
          clearPendingWorkspaceLogoPreview();
          setPendingWorkspaceLogoRemoval(false);
        }
        applyWorkspacePartialResult(error.workspace, { preservePendingLogo: logoFailed });
      }
      setWorkspaceError(error && error.publicMessage ? error.publicMessage : fallbackMessage);
    }).finally(() => {
      if (workspaceScopeCurrent() && workspaceLoadRequestRef.current === requestId) setSavingWorkspace(false);
    });
  };

  const retryWorkspaceLoad = () => {
    if (loadingWorkspace || workspaceLoadInFlightRef.current) return;
    clearWorkspaceSaveFeedback();
    setWorkspaceError('');
    setWorkspaceLoadFailed(false);
    setWorkspaceLoadRetryToken((token) => token + 1);
  };

  const openWorkspaceLogoPicker = () => {
    if (!workspaceActionAllowed('canMutateWorkspaceContent')) return;
    if (!workspaceLoaded || !workspaceCanEdit || loadingWorkspace || savingWorkspace) return;
    if (workspaceLogoInputRef.current) workspaceLogoInputRef.current.click();
  };

  const handleWorkspaceLogoFile = (event) => {
    if (!workspaceActionAllowed('canMutateWorkspaceContent')) return;
    const file = event.target.files && event.target.files[0];
    event.target.value = '';
    if (!workspaceLoaded || !workspaceCanEdit || loadingWorkspace || savingWorkspace || !file) return;
    clearWorkspaceSaveFeedback();
    if (!/^image\/(png|jpe?g|webp)$/i.test(file.type)) {
      setWorkspaceError('Please choose a PNG, JPG, JPEG, or WebP image.');
      return;
    }
    if (typeof file.size === 'number' && file.size > 4 * 1024 * 1024) {
      setWorkspaceError('Please choose an image smaller than 4 MB.');
      return;
    }
    if (!window.URL || typeof window.URL.createObjectURL !== 'function') {
      setWorkspaceError('The image could not be prepared. Please try another file.');
      return;
    }
    if (pendingWorkspaceLogoUrlRef.current && typeof window.URL.revokeObjectURL === 'function') {
      window.URL.revokeObjectURL(pendingWorkspaceLogoUrlRef.current);
    }
    const objectUrl = window.URL.createObjectURL(file);
    pendingWorkspaceLogoUrlRef.current = objectUrl;
    setPendingWorkspaceLogoFile(file);
    setPendingWorkspaceLogoUrl(objectUrl);
    setPendingWorkspaceLogoRemoval(false);
    workspaceDirtyRef.current = true;
    setWorkspaceError('');
    setSaved('');
  };

  const stageWorkspaceLogoRemoval = () => {
    if (!workspaceActionAllowed('canMutateWorkspaceContent')) return;
    if (!workspaceLoaded || !workspaceCanEdit || loadingWorkspace || savingWorkspace || !canRemoveWorkspaceLogo) return;
    clearWorkspaceSaveFeedback();
    clearPendingWorkspaceLogoPreview();
    setPendingWorkspaceLogoRemoval(true);
    workspaceDirtyRef.current = true;
    setWorkspaceError('');
    setSaved('');
  };

  const renderProfile = () =>
  <div className='rl-settings-profile-tab' data-settings-panel='profile'>
      <section className='rl-settings-section rl-settings-section--profile' aria-labelledby='settings-profile-heading'>
        <div className='rl-settings-section__head'>
          <h2 id='settings-profile-heading'>Your profile</h2>
          <p>Manage how your name and profile image appear across your workspace.</p>
        </div>
        <div className='rl-settings-profile-grid'>
          <div className='rl-settings-profile-fields'>
            <div className='rl-settings-profile-form'>
              <div className='rl-settings-name-field'>
                <SettingsField label='First name'>
                  <input className='rl-input' value={profileDraft.firstName || ''} onChange={(e) => { clearProfileSaveFeedback(); setProfileDraft((draft) => ({ ...draft, firstName: e.target.value })); setSaved(''); }} />
                </SettingsField>
              </div>
              <div className='rl-settings-name-field'>
                <SettingsField label='Last name'>
                  <input className='rl-input' value={profileDraft.lastName || ''} onChange={(e) => { clearProfileSaveFeedback(); setProfileDraft((draft) => ({ ...draft, lastName: e.target.value })); setSaved(''); }} />
                </SettingsField>
              </div>
              <div className='rl-settings-profile-save'>
                <button type='button' className='rl-btn rl-btn--primary' onClick={saveProfile} disabled={profileSaveDisabled}>
                  {profileSaveButtonLabel}
                </button>
              </div>
            </div>
            {profileError && <p className='rl-settings-profile__error'>{profileError}</p>}
          </div>
          <div className='rl-settings-photo-panel'>
            <span className='rl-settings-photo-panel__label'>Profile picture</span>
            <div className='rl-settings-avatar-control'>
              <button type='button' className='rl-settings-avatar-button' onClick={openAvatarPicker} aria-label='Change profile picture'>
                <span className='rl-settings-avatar rl-settings-avatar--profile-photo' aria-hidden='true'>
                  {profileAvatarUrl ? <img src={profileAvatarUrl} alt='' /> : profileInitials}
                </span>
              </button>
              {canRemoveAvatar && <button type='button' className='rl-settings-avatar-remove-overlay' onClick={removeAvatar} aria-label='Remove profile picture'>Remove</button>}
              <button type='button' className='rl-settings-avatar-upload' onClick={openAvatarPicker} aria-label='Upload profile picture'><i data-lucide='arrow-up'></i></button>
              <input ref={avatarInputRef} className='rl-settings-avatar-input' type='file' accept='image/png,image/jpeg,image/webp' onChange={handleAvatarFile} />
            </div>
          </div>
        </div>
      </section>
      <section className='rl-settings-section' aria-labelledby='settings-email-heading'>
        <div className='rl-settings-section__head'>
          <h2 id='settings-email-heading'>Email address</h2>
          <p>Manage your verified account login email.</p>
        </div>
        <AccountEmailChangePanel loginEmail={loginEmail} userId={user?.id || user?.userId || accountSecurity.userId} disabled={profileChanged || savingProfile} reverify={requestNativeReverification} runSensitiveAction={runSensitiveAccountAction} onConfirmed={(result) => {
          applyAccountSecurityState(result.security);
          const next = { ...user, email: result.email };
          setProfileDraft((draft) => ({ ...draft, email: result.email }));
          if (onSaveProfile) onSaveProfile(next);
          workspaceDirectoryRequestRef.current += 1;
          workspaceDirectoryLoadInFlightRef.current = false;
          setWorkspaceDirectory(createWorkspaceDirectoryState(workspaceDirectoryWorkspaceId));
          setWorkspaceDirectoryRetryToken((token) => token + 1);
        }} />
      </section>
      <section className='rl-settings-section' aria-labelledby='settings-security-heading'>
        <div className='rl-settings-section__head'>
          <h2 id='settings-security-heading'>Login &amp; security</h2>
          <p>Manage your password, multi-factor authentication, and active sessions.</p>
        </div>
        <div className='rl-settings-security-group'>
          <div className='rl-settings-security-row'>
            <span className='rl-settings-security-row__icon' aria-hidden='true'><i data-lucide='key-round'></i></span>
            <div className='rl-settings-security-row__text'><h3>Password</h3><p>{passwordRowDescription}</p>{connectedProviderText && <span className='rl-settings-security-provider'>{connectedProviderText}</span>}</div>
            <button type='button' className='rl-btn rl-btn--secondary' onClick={openPasswordDialog} disabled={accountSecurity.loading}>{accountSecurity.loading ? 'Loading...' : passwordRowAction}</button>
          </div>
          <div className='rl-settings-security-row'>
            <span className='rl-settings-security-row__icon' aria-hidden='true'><i data-lucide='shield-check'></i></span>
            <div className='rl-settings-security-row__text'><h3>Multi-factor authentication</h3><p>{mfaRowDescription}</p><span className='rl-settings-security-provider'>{mfaRowStatus}</span>{securityBackupCodeEnabled && <span className='rl-settings-security-provider'>Recovery codes created</span>}</div>
            <button type='button' className='rl-btn rl-btn--secondary' onClick={mfaRowCanOpen ? openMfaDialog : undefined} disabled={mfaRowDisabled}>{accountSecurity.loading ? 'Loading...' : mfaRowAction}</button>
          </div>
          <div className='rl-settings-security-row'>
            <span className='rl-settings-security-row__icon' aria-hidden='true'><i data-lucide='monitor-smartphone'></i></span>
            <div className='rl-settings-security-row__text'><h3>Active sessions</h3><p>Review and sign out sessions on other devices.</p></div>
            <button type='button' className='rl-btn rl-btn--secondary' onClick={openSessionsDialog}>Review sessions</button>
          </div>
        </div>
        {accountSecurityNotice && <p className='rl-settings-helper' role='status'>{accountSecurityNotice}</p>}
        {accountSecurityError && <p className='rl-settings-profile__error' role='alert'>{accountSecurityError}</p>}
      </section>
    </div>;

  const renderWorkspace = () =>
  <div className="rl-settings-workspace-tab">
      <section className="rl-settings-section rl-settings-section--workspace-details">
        <div className="rl-settings-section__head">
          <h2>Your workspace</h2>
          <p>Manage your workspace name, website, and logo.</p>
        </div>
        <div className="rl-settings-workspace-details-grid">
          <div className="rl-settings-workspace-fields">
            <SettingsField label="Workspace name">
              <input className="rl-input" value={workspaceDraft.name || ""} readOnly={!workspaceLoaded || !workspaceCanEdit || loadingWorkspace || savingWorkspace} onChange={(e) => { if (!workspaceCanEdit || !workspaceActionAllowed('canMutateWorkspaceContent') || loadingWorkspace || savingWorkspace) return; clearWorkspaceSaveFeedback(); workspaceDirtyRef.current = true; setWorkspaceDraft((draft) => ({ ...draft, name: e.target.value })); setWorkspaceError(''); setSaved(''); }} />
            </SettingsField>
            <SettingsField label="Website">
              <input className="rl-input" type="text" inputMode="url" placeholder="https://ranklyx.com" value={workspaceDraft.website || ""} readOnly={!workspaceLoaded || !workspaceCanEdit || loadingWorkspace || savingWorkspace} onChange={(e) => { if (!workspaceCanEdit || !workspaceActionAllowed('canMutateWorkspaceContent') || loadingWorkspace || savingWorkspace) return; clearWorkspaceSaveFeedback(); workspaceDirtyRef.current = true; setWorkspaceDraft((draft) => ({ ...draft, website: e.target.value, websiteUrl: e.target.value || null })); setWorkspaceError(''); setSaved(''); }} />
            </SettingsField>
            <div className="rl-settings-workspace-save">
              <button type="button" className="rl-btn rl-btn--primary" onClick={saveWorkspace} disabled={workspaceSaveDisabled}>{workspaceSaveButtonLabel}</button>
            </div>
            {workspaceLoaded && !workspaceAdmin && <p className="rl-settings-helper">Workspace admin access is required to change these settings.</p>}
            {workspaceError && <p className="rl-settings-profile__error">{workspaceError}</p>}
            {workspaceLoadFailed && <button type="button" className="rl-btn rl-btn--secondary" onClick={retryWorkspaceLoad} disabled={loadingWorkspace}>Try again</button>}
          </div>
          <div className="rl-settings-workspace-logo-panel">
            <span className="rl-settings-workspace-logo-panel__label">Workspace logo</span>
            <div className="rl-settings-workspace-logo-panel__body">
              <div className="rl-settings-workspace-logo-control">
                <button type="button" className="rl-settings-workspace-logo-button" onClick={openWorkspaceLogoPicker} aria-label="Change workspace logo" disabled={!workspaceLoaded || !workspaceCanEdit || loadingWorkspace || savingWorkspace}>
                  <span className="rl-settings-avatar rl-settings-avatar--workspace rl-settings-avatar--workspace-logo" aria-hidden="true">
                    {workspaceLogoUrl ? <img src={workspaceLogoUrl} alt="" /> : workspaceInitials}
                  </span>
                </button>
                {canRemoveWorkspaceLogo && <button type="button" className="rl-settings-workspace-logo-remove-overlay" onClick={stageWorkspaceLogoRemoval} aria-label="Remove workspace logo" disabled={!workspaceLoaded || loadingWorkspace || savingWorkspace}>Remove</button>}
                <button type="button" className="rl-settings-workspace-logo-upload" onClick={openWorkspaceLogoPicker} aria-label="Upload workspace logo" disabled={!workspaceLoaded || !workspaceCanEdit || loadingWorkspace || savingWorkspace}><i data-lucide="arrow-up"></i></button>
                <input ref={workspaceLogoInputRef} className="rl-settings-avatar-input" type="file" accept="image/png,image/jpeg,image/webp" onChange={handleWorkspaceLogoFile} disabled={!workspaceLoaded || !workspaceCanEdit || loadingWorkspace || savingWorkspace} />
              </div>
            </div>
          </div>
        </div>
      </section>

      <section className="rl-settings-section rl-settings-section--your-workspaces" aria-labelledby="settings-your-workspaces-heading">
        <div className="rl-settings-section__head">
          <h2 id="settings-your-workspaces-heading">Your workspaces</h2>
          <p>Switch between the workspaces connected to your ClickLyx account.</p>
        </div>
        <WorkspaceMembershipList
          id="settings-your-workspaces-list"
          variant="settings"
          workspace={workspace}
          state={workspaceMemberships.state}
          switchingId={workspaceSettingsSwitchingId}
          switchError={workspaceSettingsSwitchError}
          onSelect={handleSettingsWorkspaceSwitch}
          onRetry={workspaceMemberships.loadInitial}
          onLoadMore={workspaceMemberships.loadMore} />
      </section>

      <section className="rl-settings-section rl-settings-section--workspace-team">
        <div className="rl-settings-section__head rl-settings-section__head--with-action">
          <div>
            <h2>Team members</h2>
            <p>View the people who can access this workspace.</p>
          </div>
          <div className="rl-settings-team-actions">
            {workspaceDirectory.loaded && <span className="rl-settings-team-count">{workspaceDirectoryMembersTotal} {workspaceDirectoryMembersTotal === 1 ? 'member' : 'members'}</span>}
            {workspaceDirectoryCanInvite && <button ref={workspaceInviteButtonRef} type="button" className="rl-btn rl-btn--secondary" onClick={openWorkspaceInviteDialog} disabled={workspaceInviteButtonDisabled}>Invite member</button>}
          </div>
        </div>
        {workspaceInvitationNotice && <p className="rl-settings-dialog-notice" role="status">{workspaceInvitationNotice}</p>}
        {workspaceMemberNotice && <p className="rl-settings-dialog-notice" role="status">{workspaceMemberNotice}</p>}
        {workspaceMemberError && <p className="rl-settings-dialog-error" role="alert">{workspaceMemberError}</p>}
        {workspaceMemberMutationUnavailable && <p className="rl-settings-dialog-error" role="alert">Workspace member changes are unavailable right now.</p>}
        {workspaceDirectory.error && <div className="rl-settings-directory-alert" role="alert">
          <p className="rl-settings-profile__error">{workspaceDirectory.error}</p>
          <button type="button" className="rl-btn rl-btn--secondary" onClick={retryWorkspaceDirectoryLoad} disabled={workspaceDirectoryBusy}>Try again</button>
        </div>}
        {workspaceDirectoryInitialLoading && <p className="rl-settings-empty">Loading workspace members...</p>}
        {workspaceDirectory.loaded && !workspaceDirectory.error && !workspaceDirectoryMembers.length && <p className="rl-settings-empty">No workspace members found.</p>}
        {workspaceDirectoryMembers.length > 0 && <div className="rl-settings-team-table" role="table" aria-label="Workspace team members">
          <div className="rl-settings-team-table__header" role="row">
            <span className="rl-settings-team-cell rl-settings-team-cell--member" role="columnheader">Member</span>
            <span className="rl-settings-team-cell rl-settings-team-cell--role" role="columnheader">Role</span>
            <span className="rl-settings-team-cell rl-settings-team-cell--status" role="columnheader">Status</span>
            <span className="rl-settings-team-cell rl-settings-team-cell--actions" role="columnheader">Actions</span>
          </div>
          {workspaceDirectoryMembers.map((member) => {
            const roleSupported = isWorkspaceMemberRoleSupported(member.role);
            const roleValue = getWorkspaceMemberRoleSelectValue(member);
            const roleSelectLabel = getWorkspaceMemberRoleSelectLabel(roleValue);
            const finalAdministrator = member.role === 'org:admin' && workspaceDirectoryAdminCount <= 1;
            const roleActionBusy = workspaceMemberAction.membershipId === member.membershipId && workspaceMemberAction.mode === 'role';
            const removeActionBusy = workspaceMemberAction.membershipId === member.membershipId && workspaceMemberAction.mode === 'remove';
            const showRoleControl = canShowWorkspaceMemberRoleControl(member, workspaceDirectoryCanChangeRoles, workspaceMemberMutationRuntimeAvailable) && workspaceMemberRoleOptionExists(roleValue);
            const showRemoveControl = canShowWorkspaceMemberRemoveControl(member, workspaceDirectoryCanRemoveMembers, workspaceMemberMutationRuntimeAvailable);
            const roleControlDisabled = workspaceDirectoryBusy || finalAdministrator;
            const removeControlDisabled = workspaceDirectoryBusy || finalAdministrator;
            return <div className="rl-settings-team-row" role="row" key={member.membershipId}>
              <span className="rl-settings-team-cell rl-settings-team-cell--member rl-settings-team-member" role="cell">
                <span className="rl-settings-member__avatar" aria-hidden="true">
                  {member.imageUrl ? <img src={member.imageUrl} alt="" /> : member.initials}
                </span>
                <span className="rl-settings-team-member__identity">
                  <span className="rl-settings-team-member__name"><strong>{member.displayName}</strong>{member.isCurrentUser && <span className="rl-settings-team-you">You</span>}</span>
                  <small>{member.emailAddress || "No email available"}</small>
                  <small>{member.joinedAt ? 'Joined ' + member.joinedAtLabel : 'Join date unavailable'}</small>
                </span>
              </span>
              <span className="rl-settings-team-cell rl-settings-team-cell--role" role="cell" data-label="Role">
                {showRoleControl ? <span className="rl-settings-member-role-stack"><span className={'rl-settings-member-role-control' + (roleControlDisabled ? ' rl-settings-member-role-control--disabled' : '')}><span className="rl-settings-member-role-value" aria-hidden="true">{roleSelectLabel}</span><span className="rl-settings-member-role-chevron" aria-hidden="true"></span><select className="rl-input rl-settings-role-select" aria-label={'Role for ' + member.displayName} value={roleValue} onChange={(event) => updateWorkspaceMemberRole(member, event.target.value)} disabled={roleControlDisabled}>{WORKSPACE_INVITATION_ROLE_OPTIONS.map((option) => <option key={option.value} value={option.value} disabled={member.role === 'org:member' && option.value === 'org:admin' && !workspaceCanGrowTeam}>{option.label}</option>)}</select></span>{roleActionBusy && <small>Updating...</small>}{finalAdministrator && <small>Final Administrator</small>}</span> : <span className="rl-settings-role-badge">{member.roleLabel}</span>}
              </span>
              <span className="rl-settings-team-cell rl-settings-team-cell--status" role="cell" data-label="Status"><span className="rl-settings-status-pill">Active</span></span>
              <span className="rl-settings-team-cell rl-settings-team-cell--actions" role="cell" data-label="Actions"><span className="rl-settings-member-actions">{workspaceDirectoryCanManageMembers ? member.isCurrentUser ? <small>Current user</small> : showRemoveControl ? <button type="button" className="rl-btn rl-btn--secondary rl-btn--danger" onClick={() => requestRemoveWorkspaceMember(member)} disabled={removeControlDisabled}>{removeActionBusy ? 'Removing...' : 'Remove member'}</button> : <small>{roleSupported ? 'No actions' : 'Unsupported role'}</small> : <small>Member access</small>}</span></span>
            </div>;
          })}
        </div>}
        {workspaceDirectory.membersPage && workspaceDirectory.membersPage.hasMore && <div className="rl-settings-load-more-row">
          <button type="button" className="rl-btn rl-btn--secondary" onClick={() => loadWorkspaceDirectoryPage('members')} disabled={workspaceDirectoryBusy}>{workspaceDirectory.loadingMoreMembers ? 'Loading...' : 'Load more members'}</button>
        </div>}
        {workspaceDirectory.invitationsVisible && <div className="rl-settings-invitations" aria-label="Pending workspace invitations">
          <div className="rl-settings-subsection-head">
            <h3>Pending invitations</h3>
            {workspaceDirectory.loaded && <span>{workspaceDirectoryInvitationsTotal} pending</span>}
          </div>
          {!workspaceDirectory.loading && !workspaceDirectory.error && !workspaceDirectoryInvitations.length && <p className="rl-settings-empty">No pending invitations.</p>}
          {workspaceDirectoryInvitations.length > 0 && <div className="rl-settings-team-table rl-settings-team-table--invitations" role="table" aria-label="Pending workspace invitations">
            <div className="rl-settings-team-table__header" role="row">
              <span className="rl-settings-team-cell rl-settings-team-cell--member" role="columnheader">Invitee</span>
              <span className="rl-settings-team-cell rl-settings-team-cell--role" role="columnheader">Role</span>
              <span className="rl-settings-team-cell rl-settings-team-cell--status" role="columnheader">Status</span>
              <span className="rl-settings-team-cell rl-settings-team-cell--actions" role="columnheader">Actions</span>
            </div>
            {workspaceDirectoryInvitations.map((invitation) =>
            <div className="rl-settings-team-row" role="row" key={invitation.invitationId}>
              <span className="rl-settings-team-cell rl-settings-team-cell--member rl-settings-team-member" role="cell">
                <span className="rl-settings-member__avatar rl-settings-member__avatar--pending" aria-hidden="true">{getInitials(invitation.emailAddress, 'IN')}</span>
                <span className="rl-settings-team-member__identity">
                  <strong>{invitation.emailAddress || 'Pending invitee'}</strong>
                  <small>{invitation.expiresAt ? 'Expires ' + invitation.expiresAtLabel : 'Expiration unavailable'}</small>
                </span>
              </span>
              <span className="rl-settings-team-cell rl-settings-team-cell--role" role="cell" data-label="Role"><span className="rl-settings-role-badge">{invitation.roleLabel}</span></span>
              <span className="rl-settings-team-cell rl-settings-team-cell--status" role="cell" data-label="Status"><span className="rl-settings-status-pill rl-settings-status-pill--pending">{invitation.statusLabel}</span></span>
              <span className="rl-settings-team-cell rl-settings-team-cell--actions" role="cell" data-label="Actions"><span className="rl-settings-invitation-actions"><small>Sent {invitation.createdAtLabel}</small>{workspaceDirectoryCanInvite && <button type="button" className="rl-btn rl-btn--secondary" onClick={() => requestCancelWorkspaceInvitation(invitation)} disabled={workspaceDirectoryBusy || workspaceCancelInvitationBusy}>Cancel invitation</button>}</span></span>
            </div>
            )}
          </div>}
          {workspaceDirectory.invitationsPage && workspaceDirectory.invitationsPage.hasMore && <div className="rl-settings-load-more-row">
            <button type="button" className="rl-btn rl-btn--secondary" onClick={() => loadWorkspaceDirectoryPage('invitations')} disabled={workspaceDirectoryBusy}>{workspaceDirectory.loadingMoreInvitations ? 'Loading...' : 'Load more invitations'}</button>
          </div>}
        </div>}
      </section>

      <section className="rl-settings-section rl-settings-section--workspace-roles">
        <div className="rl-settings-section__head">
          <h2>Roles & permissions</h2>
          <p>Understand what each workspace role can manage.</p>
        </div>
        <div className="rl-settings-role-rows">
          <div className="rl-settings-role-row">
            <strong>Administrator</strong>
            <span>Can manage workspace settings, members, and invitations.</span>
          </div>
          <div className="rl-settings-role-row">
            <strong>Member</strong>
            <span>Can create and manage content within the workspace.</span>
          </div>
        </div>
        <p className="rl-settings-role-helper">Administrators can manage roles and remove members. Every Workspace keeps at least one Administrator.</p>
      </section>

      {workspaceAdmin ? <section className="rl-settings-section rl-settings-section--workspace-plan">
        <div className="rl-settings-section__head">
          <h2>Plan details</h2>
          <p>Review the current plan and remaining article credits.</p>
        </div>
        <div className="rl-settings-plan-summary">
          <span>
            <small>Current plan</small>
            <strong>{commercialPresentation.plan}</strong>
          </span>
          <span>
            <small>Credits remaining</small>
            <strong>{creditRemainingText}</strong>
          </span>
          <span>
            <small>Current billing cycle</small>
            <strong>{commercialPresentation.billingCycle}</strong>
          </span>
          <button type="button" className="rl-btn rl-btn--secondary" onClick={() => { setSelected("billing"); setSaved(""); }}>View billing & credits</button>
        </div>
        {commercialPresentation.note && <p className="rl-settings-note">{commercialPresentation.note}</p>}
      </section> : <section className="rl-settings-section rl-settings-section--workspace-plan">
        <div className="rl-settings-section__head">
          <h2>Article usage</h2>
          <p>Review Articles used and remaining in this workspace.</p>
        </div>
        <div className="rl-settings-plan-summary">
          <span>
            <small>Total Articles</small>
            <strong>{creditTotalText}</strong>
          </span>
          <span>
            <small>Articles used</small>
            <strong>{creditConsumedText}</strong>
          </span>
          <span>
            <small>Articles remaining</small>
            <strong>{creditRemainingText}</strong>
          </span>
          <button type="button" className="rl-btn rl-btn--secondary" onClick={() => { setSelected("billing"); setSaved(""); }}>View Article usage</button>
        </div>
        {creditStateMessage && <p className="rl-settings-note">{creditStateMessage}</p>}
      </section>}

      <section className="rl-settings-section rl-settings-section--workspace-danger">
        <div className="rl-settings-section__head">
          <h2>Danger zone</h2>
          <p>These actions affect access to this workspace and its saved data.</p>
        </div>
        <div className="rl-settings-workspace-danger-box">
          <div className="rl-settings-danger-row">
            <span>
              <strong>Leave workspace</strong>
              <small>Remove your access to this workspace.</small>
            </span>
            <button type="button" className="rl-btn rl-btn--secondary" disabled>Leave workspace</button>
          </div>
          <div className="rl-settings-danger-row">
            <span>
              <strong>Delete workspace</strong>
              <small>Permanently delete this workspace and its associated data.</small>
            </span>
            <button type="button" className="rl-btn rl-btn--secondary" disabled>Delete workspace</button>
          </div>
          <p>Workspace deletion will require confirmation and appropriate administrator permissions.</p>
        </div>
      </section>
    </div>;

  const handleManageBilling = (paymentMethodUpdate = false) => {
    if (!workspaceAdmin || billingPortalState.status === 'loading' || billingPortalInFlightRef.current) return;
    const runtime = getWorkspaceCommercialRuntime();
    const auth = window.RankLyxAuth;
    if (!runtime || typeof runtime.openBillingPortalSessionInNewTab !== 'function'
      || !auth || typeof auth.authenticatedFetch !== 'function') {
      setBillingPortalState({
        status: 'error',
        error: 'Billing management is unavailable right now. Please try again.'
      });
      return;
    }
    const operation = runtime.openBillingPortalSessionInNewTab(
      (endpoint, options) => auth.authenticatedFetch(endpoint, options),
      (url, target) => window.open(url, target),
      billingPortalInFlightRef,
      paymentMethodUpdate === true ? 'payment_method_update' : undefined
    );
    if (!operation) return;
    setBillingPortalState({ status: 'loading', error: '' });
    Promise.resolve(operation).then(() => {
      if (settingsMountedRef.current) setBillingPortalState({ status: 'idle', error: '' });
    }).catch(() => {
      if (!settingsMountedRef.current) return;
      setBillingPortalState({
        status: 'error',
        error: 'Billing management is unavailable right now. Please try again.'
      });
    });
  };

  const renderCredits = () =>
  <div className="rl-settings-card" data-settings-panel="credits">
      <div className="rl-settings-card__head">
        <div>
          <h2>Article usage</h2>
          <p>Review Articles used and remaining in this workspace.</p>
        </div>
      </div>
      <div className="rl-settings-billing-grid">
        <div className="rl-settings-metric">
          <span>Total Articles</span>
          <strong>{creditTotalText}</strong>
        </div>
        <div className="rl-settings-metric">
          <span>Articles used</span>
          <strong>{creditConsumedText}</strong>
        </div>
        <div className="rl-settings-metric">
          <span>Articles remaining</span>
          <strong>{creditRemainingText}</strong>
        </div>
      </div>
      {creditStateMessage && <p className="rl-settings-note" role={creditState && creditState.status === 'error' ? 'alert' : 'status'}>{creditStateMessage}</p>}
    </div>;

  const requestSubscriptionCancellationChange = () => {
    if (!subscriptionActionAvailable || subscriptionMutationBusy) return;
    const mode = subscriptionCancellationAction.mode;
    const retentionStatus = authoritativeRetentionOffer && authoritativeRetentionOffer.status || 'unavailable';
    setSubscriptionMutationState({ status: 'idle', workspaceId: settingsWorkspaceId, desiredCancellationScheduled: null, error: '' });
    setSubscriptionConfirmation({
      workspaceId: settingsWorkspaceId,
      mode,
      step: mode === 'keep' ? 'reverse_confirm' : 'step1',
      periodEnd: subscriptionPeriodEnd,
      periodEndLabel: subscriptionPeriodEndLabel,
      retentionStatus,
      reason: '',
      comment: '',
      validation: '',
      secondChanceDeclined: false,
      retentionSource: 'first'
    });
  };

  const closeSubscriptionConfirmation = () => {
    if (subscriptionMutationState.status === 'submitting') return;
    setSubscriptionConfirmation(null);
    if (subscriptionMutationState.status === 'pending') return;
    setSubscriptionMutationState({ status: 'idle', workspaceId: settingsWorkspaceId, desiredCancellationScheduled: null, error: '' });
  };

  const updateSubscriptionFlow = (patch) => {
    setSubscriptionConfirmation((current) => current ? { ...current, ...patch } : current);
  };

  const subscriptionFeedback = () => {
    if (!subscriptionConfirmation || !commercialRuntime || typeof commercialRuntime.normalizeCancellationFeedback !== 'function') return null;
    try {
      return commercialRuntime.normalizeCancellationFeedback(subscriptionConfirmation.reason, subscriptionConfirmation.comment);
    } catch (feedbackError) {
      const reason = subscriptionConfirmation.reason;
      const validation = !reason
        ? 'Please select one reason why you want to cancel your subscription.'
        : feedbackError && feedbackError.message === 'workspace_cancellation_comment_required'
          ? 'Please tell us a little more about why you’re cancelling.'
          : 'Please keep your comment to 500 characters or fewer and use standard text.';
      updateSubscriptionFlow({
        validation
      });
      return null;
    }
  };

  const continueCancellationReason = () => {
    const feedback = subscriptionFeedback();
    if (!feedback) return;
    const secondChance = subscriptionConfirmation.retentionStatus === 'eligible'
      && !subscriptionConfirmation.secondChanceDeclined
      && commercialRuntime.SECOND_CHANCE_REASONS.includes(feedback.reason);
    updateSubscriptionFlow({ step: secondChance ? 'second_chance' : 'final_confirm', validation: '' });
  };

  const runSubscriptionMutation = (action, feedback, pendingStep, successStep, failureStep) => {
    if (!subscriptionConfirmation || subscriptionMutationBusy || !subscriptionActionAvailable) return;
    const expectedMode = action === 'reverse' ? 'keep' : 'schedule';
    if (subscriptionConfirmation.workspaceId !== settingsWorkspaceId
      || subscriptionConfirmation.periodEnd !== subscriptionPeriodEnd
      || subscriptionCancellationAction.mode !== expectedMode) {
      setSubscriptionConfirmation(null);
      setSubscriptionMutationState({ status: 'error', workspaceId: settingsWorkspaceId, desiredCancellationScheduled: null, error: 'Billing details changed. Review the current subscription and try again.' });
      if (typeof refreshCommercial === 'function') Promise.resolve(refreshCommercial(settingsWorkspaceId)).catch(() => null);
      return;
    }
    const coordinator = subscriptionMutationCoordinatorRef.current;
    if (!coordinator) {
      setSubscriptionMutationState({ status: 'error', workspaceId: settingsWorkspaceId, desiredCancellationScheduled: null, error: 'We couldn’t update your subscription right now. Please try again.' });
      updateSubscriptionFlow({ step: failureStep });
      return;
    }
    const workspaceId = subscriptionConfirmation.workspaceId;
    const desiredCancellationScheduled = action === 'schedule' ? true : action === 'reverse' ? false : null;
    let operation;
    try {
      operation = coordinator.submit({ workspaceId, action, feedback });
    } catch (submitError) {
      operation = Promise.reject(submitError);
    }
    if (!operation) return;
    setSubscriptionMutationState({ status: 'submitting', workspaceId, desiredCancellationScheduled, error: '' });
    updateSubscriptionFlow({ step: pendingStep, validation: '' });

    Promise.resolve(operation).then(async (result) => {
      const scope = subscriptionMutationScopeRef.current;
      if (!settingsMountedRef.current || !result || result.stale
        || scope.workspaceId !== workspaceId || scope.administrator !== true) return;
      if (action !== 'retention') {
        const isCurrent = () => settingsMountedRef.current
          && subscriptionMutationScopeRef.current.workspaceId === workspaceId
          && subscriptionMutationScopeRef.current.administrator === true;
        const confirmedEnd = result.result && result.result.periodEnd;
        const refreshed = confirmedEnd === subscriptionConfirmation.periodEnd
          ? await commercialRuntime.refreshCancellationProjection(refreshCommercial, workspaceId,
            desiredCancellationScheduled, confirmedEnd, isCurrent)
          : { stale: !isCurrent(), converged: false };
        if (refreshed.stale || !isCurrent()) return;
        if (!refreshed.converged) {
          setSubscriptionMutationState({ status: 'pending', workspaceId, desiredCancellationScheduled, periodEnd: confirmedEnd, error: '' });
          updateSubscriptionFlow({ step: action === 'schedule' ? 'cancel_sync_pending' : 'reverse_sync_pending' });
          return;
        }
      } else if (typeof refreshCommercial === 'function') await Promise.resolve(refreshCommercial(workspaceId)).catch(() => null);
      const latestScope = subscriptionMutationScopeRef.current;
      if (!settingsMountedRef.current || latestScope.workspaceId !== workspaceId || latestScope.administrator !== true) return;
      setSubscriptionMutationState({ status: 'idle', workspaceId, desiredCancellationScheduled, error: '' });
      updateSubscriptionFlow(action === 'retention' ? { step: successStep } : {
        step: successStep,
        periodEnd: result.result.periodEnd,
        periodEndLabel: commercialRuntime.formatBillingDate(result.result.periodEnd)
      });
    }).catch((requestError) => {
      const scope = subscriptionMutationScopeRef.current;
      if (!settingsMountedRef.current || scope.workspaceId !== settingsWorkspaceId || scope.administrator !== true) return;
      const status = Number(requestError && requestError.status) || 0;
      const message = action === 'retention'
        ? 'We couldn’t apply the offer. Nothing was changed. Please try again.'
        : action === 'schedule'
          ? 'We couldn’t schedule cancellation. Nothing was changed. Please try again.'
          : 'We couldn’t keep your subscription right now. Please try again.';
      setSubscriptionMutationState({ status: 'error', workspaceId: settingsWorkspaceId, desiredCancellationScheduled, error: message });
      updateSubscriptionFlow({ step: failureStep });
      if ((status === 409 || status === 403) && typeof refreshCommercial === 'function') Promise.resolve(refreshCommercial(settingsWorkspaceId)).catch(() => null);
    });
  };

  const acceptRetentionOffer = () => {
    const second = subscriptionConfirmation && (subscriptionConfirmation.step === 'second_chance'
      || subscriptionConfirmation.retentionSource === 'second');
    const feedback = second ? subscriptionFeedback() : null;
    if (second && !feedback) return;
    updateSubscriptionFlow({ retentionSource: second ? 'second' : 'first' });
    runSubscriptionMutation('retention', feedback, 'applying_retention', 'retention_success', 'retention_error');
  };

  const confirmFinalCancellation = () => {
    const feedback = subscriptionFeedback();
    if (!feedback) return;
    runSubscriptionMutation('schedule', feedback, 'scheduling_cancel', 'cancel_success', 'final_confirm');
  };

  const confirmCancellationReversal = () => {
    runSubscriptionMutation('reverse', null, 'reversing', 'reverse_success', 'reverse_confirm');
  };

  const selectCheckoutBillingInterval = (billingInterval) => {
    if (!['monthly', 'annual'].includes(billingInterval)
      || ['creating', 'redirecting', 'current_subscription', 'completion_pending'].includes(checkoutState.status)) return;
    const coordinator = checkoutCoordinatorRef.current;
    if (coordinator) coordinator.resetSelection(settingsWorkspaceId);
    setCheckoutBillingInterval(billingInterval);
    setCheckoutState({ status: 'idle', workspaceId: settingsWorkspaceId, planKey: '', billingInterval, message: '' });
  };

  const handleCheckoutPlan = (planKey, newAttempt) => {
    if (!workspaceAdmin || !settingsWorkspaceId || !checkoutCatalog || currentSubscriptionPresent) return;
    const coordinator = checkoutCoordinatorRef.current;
    if (!coordinator) {
      setCheckoutState({
        status: 'error',
        workspaceId: settingsWorkspaceId,
        planKey,
        billingInterval: checkoutBillingInterval,
        message: 'Secure checkout is unavailable right now. Please try again.'
      });
      return;
    }
    let operation;
    try {
      operation = coordinator.submit({
        workspaceId: settingsWorkspaceId,
        planKey,
        billingInterval: checkoutBillingInterval,
        newAttempt: newAttempt === true
      });
    } catch (error) {
      operation = Promise.reject(error);
    }
    if (!operation) return;
    const workspaceId = settingsWorkspaceId;
    const billingInterval = checkoutBillingInterval;
    setCheckoutState({ status: 'creating', workspaceId, planKey, billingInterval, message: '' });
    Promise.resolve(operation).then((result) => {
      const scope = checkoutScopeRef.current;
      if (!settingsMountedRef.current || !result || result.stale
        || scope.workspaceId !== workspaceId || scope.administrator !== true) return;
      setCheckoutState({
        status: 'redirecting',
        workspaceId,
        planKey,
        billingInterval,
        message: 'Opening secure checkout...'
      });
    }).catch((error) => {
      const scope = checkoutScopeRef.current;
      if (!settingsMountedRef.current || scope.workspaceId !== workspaceId || scope.administrator !== true) return;
      const code = String(error && error.code || '');
      if (code === 'workspace_checkout_current_subscription_exists') {
        setCheckoutState({
          status: 'current_subscription',
          workspaceId,
          planKey,
          billingInterval,
          message: 'Your billing details changed. We are refreshing the current subscription.'
        });
        if (typeof refreshCommercial === 'function') Promise.resolve(refreshCommercial(workspaceId)).catch(() => null);
        return;
      }
      if (code === 'workspace_checkout_completion_pending') {
        setCheckoutState({
          status: 'completion_pending',
          workspaceId,
          planKey,
          billingInterval,
          message: 'Your checkout was completed. We are confirming your subscription.'
        });
        return;
      }
      if (['workspace_checkout_session_expired', 'workspace_checkout_attempt_closed', 'workspace_checkout_idempotency_conflict'].includes(code)) {
        setCheckoutState({
          status: 'terminal',
          workspaceId,
          planKey,
          billingInterval,
          message: 'This checkout attempt is no longer available. Start a new attempt to try again.'
        });
        return;
      }
      const message = code === 'workspace_billing_mutation_in_progress'
        ? 'Another billing change is already in progress. Please try again.'
        : 'Secure checkout is unavailable right now. Nothing was changed. Please try again.';
      setCheckoutState({ status: 'error', workspaceId, planKey, billingInterval, message });
    });
  };

  const retryCheckoutCatalog = () => {
    if (!workspaceAdmin || !settingsWorkspaceId || typeof refreshCommercial !== 'function') return;
    const workspaceId = settingsWorkspaceId;
    setCheckoutState({ status: 'catalog_loading', workspaceId, planKey: '', billingInterval: checkoutBillingInterval, message: 'Loading plans...' });
    Promise.resolve(refreshCommercial(workspaceId)).then((result) => {
      const scope = checkoutScopeRef.current;
      if (!settingsMountedRef.current || !result || result.stale
        || scope.workspaceId !== workspaceId || scope.administrator !== true) return;
      setCheckoutState({ status: 'idle', workspaceId, planKey: '', billingInterval: checkoutBillingInterval, message: '' });
    }).catch(() => {
      const scope = checkoutScopeRef.current;
      if (!settingsMountedRef.current || scope.workspaceId !== workspaceId) return;
      setCheckoutState({ status: 'error', workspaceId, planKey: '', billingInterval: checkoutBillingInterval, message: 'Plans are unavailable right now. Please try again.' });
    });
  };

  const retryCheckoutReturn = () => {
    const coordinator = checkoutReturnCoordinatorRef.current;
    if (coordinator) Promise.resolve(coordinator.retry()).catch(() => null);
  };

  const goHomeAfterCheckout = () => {
    if (typeof onNavigate === 'function') onNavigate('dashboard');
  };

  const upgradeScopeIsCurrent = (workspaceId) => {
    const scope = upgradeScopeRef.current;
    return settingsMountedRef.current && scope.workspaceId === workspaceId && scope.administrator === true
      && getWorkspaceDirectoryId(window.currentWorkspace || workspace) === workspaceId;
  };

  const closeUpgradeConfirmation = () => {
    if (upgradeConfirmation && ['submitting', 'authenticating', 'confirming'].includes(upgradeConfirmation.status)) return;
    setUpgradeConfirmation(null);
  };

  const requestUpgradeConfirmation = (targetPlanKey) => {
    if (!workspaceAdmin || !settingsWorkspaceId || !checkoutCatalog || !authoritativeUpgradeProjection
      || authoritativeUpgradeProjection.eligible !== true
      || authoritativeUpgradeProjection.billingInterval !== checkoutBillingInterval) return;
    const tierRanks = { starter: 1, growth: 2, scale: 3 };
    if (!(tierRanks[targetPlanKey] > tierRanks[authoritativeUpgradeProjection.currentPlanKey])) return;
    const currentPlan = checkoutCatalog.plans.find((plan) => plan.planKey === authoritativeUpgradeProjection.currentPlanKey);
    const targetPlan = checkoutCatalog.plans.find((plan) => plan.planKey === targetPlanKey);
    const cadence = targetPlan && targetPlan[authoritativeUpgradeProjection.billingInterval];
    const amountLabel = commercialRuntime && typeof commercialRuntime.formatCheckoutMoney === 'function'
      ? commercialRuntime.formatCheckoutMoney(cadence && cadence.amount, checkoutCatalog.currency) : '';
    const periodEndLabel = commercialRuntime && typeof commercialRuntime.formatBillingDate === 'function'
      ? commercialRuntime.formatBillingDate(authoritativeUpgradeProjection.projectedPeriodEnd) : '';
    if (!currentPlan || !targetPlan || !cadence || !amountLabel || !periodEndLabel) return;
    setUpgradeConfirmation({
      status: 'confirm',
      workspaceId: settingsWorkspaceId,
      targetPlanKey,
      currentPlanName: currentPlan.name,
      targetPlanName: targetPlan.name,
      billingInterval: authoritativeUpgradeProjection.billingInterval,
      amountLabel,
      allowanceArticles: cadence.articles,
      targetUsers: targetPlan.includedUsers,
      targetWebsites: targetPlan.includedWebsites,
      periodEndLabel,
      retentionDiscountActive: authoritativeUpgradeProjection.retentionDiscountActive === true,
      newAttempt: upgradeRetryAllowedRef.current,
      message: ''
    });
  };

  const runUpgradeConfirmation = async (newAttempt) => {
    const flow = upgradeConfirmation;
    const coordinator = upgradeCoordinatorRef.current;
    const workspaceId = settingsWorkspaceId;
    if (!flow || flow.workspaceId !== workspaceId || !workspaceAdmin || !coordinator || upgradeRunRef.current) return;
    if (newAttempt === true && !(flow.status === 'processing_failure' && flow.retrySafe)) return;
    upgradeRunRef.current = true;
    const startedAt = Date.now();
    const activeFlow = { ...flow, startedAt, newAttempt: false, status: 'submitting', message: '' };
    setUpgradeConfirmation(activeFlow);
    let first = true;
    let authenticationAttempted = false;
    let paidResult = null;
    upgradeRetryAllowedRef.current = false;
    try {
      while (upgradeScopeIsCurrent(workspaceId)) {
      try {
      const freshAttempt = first && (newAttempt === true || flow.newAttempt === true);
      first = false;
      const envelope = paidResult ? { result: paidResult } : await coordinator.submit({
        workspaceId,
        targetPlanKey: flow.targetPlanKey,
        newAttempt: freshAttempt
      });
      if (!envelope || envelope.stale || !upgradeScopeIsCurrent(workspaceId)) return;
      let result = envelope.result;
      if (result.state === 'payment_action_required') {
        const authRuntime = window.RankLyxAuth;
        const publishableKey = authRuntime && typeof authRuntime.getStripePublishableKey === 'function'
          ? authRuntime.getStripePublishableKey() : '';
        setUpgradeConfirmation({ ...activeFlow, status: 'authenticating' });
        if (!authenticationAttempted && result.clientSecret && publishableKey && typeof window.Stripe === 'function') {
          authenticationAttempted = true;
          await commercialRuntime.confirmUpgradePayment(window.Stripe(publishableKey), result.clientSecret);
        }
      }
      if (result.state === 'completed') {
        paidResult = result;
        setUpgradeConfirmation({ ...activeFlow, status: 'confirming' });
        const accessClient = window.ClicklyxWorkspaceAccess;
        const refreshResults = await Promise.all([
          typeof refreshWorkspaceReads === 'function'
            ? refreshWorkspaceReads(workspaceId)
            : Promise.reject(new Error('workspace_upgrade_refresh_unavailable')),
          accessClient && typeof accessClient.refresh === 'function'
            ? accessClient.refresh({ reason: 'subscription_upgrade' })
            : Promise.reject(new Error('workspace_upgrade_access_refresh_unavailable'))
        ]);
        if (!upgradeScopeIsCurrent(workspaceId)) return;
        const reads = refreshResults[0];
        const accessState = refreshResults[1];
        const billing = reads && reads.billing;
        const ready = reads && reads.stale !== true && !reads.error && billing
          && billing.subscription && billing.subscription.commercialState === 'current'
          && billing.subscription.billingInterval === (flow.billingInterval === 'annual' ? 'year' : 'month')
          && billing.upgrade && billing.upgrade.currentPlanKey === flow.targetPlanKey
          && billing.plan && billing.plan.displayName
          && billing.subscription.currentPeriod && result.period
          && billing.subscription.currentPeriod.end === result.period.end
          && billing.seats && billing.seats.included === flow.targetUsers
          && reads.credits && reads.credits.articleGeneration
          && reads.credits.articleGeneration.total === result.allowance.articles + result.carriedArticles
          && accessState && accessState.workspaceId === workspaceId && accessState.status === 'full';
        if (ready) {
          if (typeof onUpgradeComplete === 'function') await Promise.resolve(onUpgradeComplete(workspaceId));
          if (!upgradeScopeIsCurrent(workspaceId)) return;
          setUpgradeConfirmation({ ...activeFlow, status: 'success', targetPlanName: billing.plan.displayName,
            periodEndLabel: commercialRuntime.formatBillingDate(billing.subscription.currentPeriod.end) });
          return;
        }
      }
      if (result.paymentResult === 'paid_provisioning_failed') {
        setUpgradeConfirmation({ ...activeFlow, status: 'provisioning_failed' });
        return;
      }
      if (result.paymentResult === 'processing_failed_no_charge') {
        upgradeRetryAllowedRef.current = true;
        setUpgradeConfirmation({ ...activeFlow, status: 'processing_failure', retrySafe: true });
        return;
      }
      if (['insufficient_funds', 'expired_payment_method', 'payment_information', 'declined'].includes(result.paymentResult)) {
        upgradeRetryAllowedRef.current = true;
        setUpgradeConfirmation({ ...activeFlow, status: 'payment_method_required', paymentProblem: result.paymentResult });
        return;
      }
      } catch (error) {
        // A transport/authentication/read failure cannot establish a failed payment.
        if (!upgradeScopeIsCurrent(workspaceId)) return;
        // Definitive request-contract rejections are terminal, not transport retries.
        // Never infer a failed payment from a canonical read after a paid result.
        if (!paidResult && error && [400, 403, 405, 409, 413, 415].includes(error.status)
          && ['workspace_subscription_upgrade_target_invalid',
            'workspace_subscription_upgrade_request_invalid',
            'workspace_subscription_upgrade_idempotency_conflict',
            'workspace_subscription_upgrade_keep_subscription_first',
            'workspace_subscription_upgrade_billing_recovery_required',
            'workspace_subscription_upgrade_not_eligible',
            'workspace_administrator_required', 'method_not_allowed',
            'workspace_subscription_upgrade_body_too_large',
            'workspace_subscription_upgrade_unsupported_media_type'].includes(error.code)) {
          setUpgradeConfirmation({ ...activeFlow, status: 'failed' });
          return;
        }
      }
      await new Promise((resolve) => setTimeout(resolve, 2000));
      }
    } finally {
      upgradeRunRef.current = false;
    }
  };

  const focusFreePlanSelection = () => {
    const heading = document.getElementById('settings-checkout-plans-title');
    if (!heading) return;
    heading.focus({ preventScroll: true });
    const reducedMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    heading.scrollIntoView({ behavior: reducedMotion ? 'auto' : 'smooth', block: 'start' });
  };

  const renderCheckoutCatalog = (activeRedesign = false, freeRedesign = false) => checkoutCatalog
    ? <CheckoutPlanSelector
        catalog={checkoutCatalog}
        heading={activeRedesign ? 'Upgrade your plan' : checkoutHeading}
        billingInterval={checkoutBillingInterval}
        checkoutState={checkoutState}
        currentPlanKey={currentCheckoutPlanKey}
        currentBillingInterval={currentCheckoutBillingInterval}
        hasCurrentSubscription={currentSubscriptionPresent}
        upgradeProjection={authoritativeUpgradeProjection}
        upgradeFlow={upgradeConfirmation}
        activeRedesign={activeRedesign}
        freeRedesign={freeRedesign}
        onBillingIntervalChange={selectCheckoutBillingInterval}
        onChoosePlan={handleCheckoutPlan}
        onChooseUpgrade={requestUpgradeConfirmation} />
    : <div className="rl-checkout-unavailable" role="alert">
        <div>
          <h3>Plans are unavailable</h3>
          <p>We could not load the current plan catalog. No guessed pricing is shown.</p>
        </div>
        <button type="button" className="rl-btn rl-btn--secondary" onClick={retryCheckoutCatalog} disabled={checkoutState.status === 'catalog_loading'}>
          {checkoutState.status === 'catalog_loading' ? 'Loading plans...' : 'Try again'}
        </button>
      </div>;

  const renderSubscriptionConfirmationNotice = () => subscriptionMutationState.status === 'pending'
    && subscriptionMutationState.workspaceId === settingsWorkspaceId
    && <p className="rl-settings-note" role="status">{subscriptionMutationState.desiredCancellationScheduled
      ? commercialRuntime.CANCELLATION_SYNC_PENDING_MESSAGE : commercialRuntime.REVERSAL_SYNC_PENDING_MESSAGE}</p>;
  const renderRedesignedBilling = () => <div className="rl-settings-card rl-billing-active" data-settings-panel="billing" data-billing-state={redesignedBillingState}>
    <div className="rl-settings-card__head rl-billing-active__head">
      <div>
        <h2>Billing & credits</h2>
        <p>Manage your workspace subscription, billing, and payment details</p>
      </div>
    </div>
    {redesignedBillingState === 'scheduled-cancellation' && <BillingLifecycleNotice
      kind="scheduled-cancellation" periodEndDate={scheduledCancellationBilling.periodEndDate}
      onStopCancellation={requestSubscriptionCancellationChange}
      disabled={!subscriptionActionAvailable || subscriptionMutationBusy} />}
    {redesignedBillingState === 'free' && <BillingLifecycleNotice
      kind="free" onUpgrade={focusFreePlanSelection} disabled={!checkoutCatalog} />}
    <CheckoutReturnNotice state={checkoutReturnState} onRetry={retryCheckoutReturn} onGoHome={goHomeAfterCheckout} />
    {redesignedBillingState !== 'free' && commercialPresentation.note && <p className="rl-settings-note" role="status">{commercialPresentation.note}</p>}
    {renderSubscriptionConfirmationNotice()}
    {redesignedBillingState === 'scheduled-cancellation' && subscriptionMutationState.status === 'error'
      && subscriptionMutationState.workspaceId === settingsWorkspaceId && !subscriptionConfirmation
      && <p className="rl-settings-note" role="alert">{subscriptionMutationState.error}</p>}

    <section className="rl-billing-active__section" aria-labelledby="billing-active-articles-title">
      <h3 className="rl-billing-active__section-bar" id="billing-active-articles-title">ARTICLES &amp; AI CREDITS</h3>
      <div className="rl-billing-active__table-wrap">
        <table className="rl-billing-active__table rl-billing-active__table--articles">
          <thead><tr><th scope="col">TYPE</th><th scope="col">DESCRIPTION</th><th scope="col">TOTAL</th><th scope="col">CONSUMED</th><th scope="col">REMAINING</th></tr></thead>
          <tbody>
            <tr><th scope="row">Articles</th><td>Articles available for generating new articles.</td><td>{redesignedBillingState === 'free' ? '0' : creditTotalText}</td><td>{redesignedBillingState === 'free' ? '0' : creditConsumedText}</td><td>{redesignedBillingState === 'free' ? '0' : creditRemainingText}</td></tr>
            <tr><th scope="row">AI Chat</th><td>Credits available for use with AI Chat. (Coming soon)</td><td>—</td><td>—</td><td>—</td></tr>
          </tbody>
        </table>
      </div>
      {creditStateMessage && <p className="rl-settings-note" role={creditState && creditState.status === 'error' ? 'alert' : 'status'}>{creditStateMessage}</p>}
    </section>

    <section className="rl-billing-active__section" aria-labelledby="billing-active-payment-title">
      <h3 className="rl-billing-active__section-bar" id="billing-active-payment-title">PAYMENT &amp; BILLING HISTORY</h3>
      <div className="rl-billing-active__table-wrap">
        <table className="rl-billing-active__table rl-billing-active__table--payment">
          <thead><tr><th scope="col">PLAN</th><th scope="col">DESCRIPTION</th><th scope="col">PLAN PRICE</th><th scope="col">SEATS</th><th scope="col">CARD</th></tr></thead>
          <tbody><tr>
            <th scope="row">{redesignedBilling.planName}</th>
            <td>{redesignedBillingState === 'free'
              ? 'You are on the Free plan and your workspace is read-only.'
              : redesignedBillingState === 'scheduled-cancellation'
                ? <>You are on {scheduledCancellationBilling.cadenceLabel === 'Annual' ? 'an' : 'a'} <strong>{scheduledCancellationBilling.cadenceLabel} Plan</strong> and your subscription will end on <strong>{scheduledCancellationBilling.periodEndDate}</strong>.</>
                : <>You are on a <strong>{healthyActiveBilling.cadenceLabel} Plan</strong> and your next charge will be on <strong>{healthyActiveBilling.nextChargeDate}</strong>.</>}</td>
            <td>{redesignedBilling.planPrice}</td>
            <td>{redesignedBilling.seats}</td>
            <td>{redesignedBilling.card}</td>
          </tr></tbody>
        </table>
      </div>
      <p className="rl-billing-active__portal-copy">Update your card and billing address, and download your past receipts <button type="button" className="rl-billing-active__text-action" aria-label="Manage billing" onClick={handleManageBilling} disabled={billingPortalState.status === 'loading'}>{billingPortalState.status === 'loading' ? 'Opening billing...' : 'here →'}</button></p>
      {billingPortalState.error && <p className="rl-settings-note" role="alert">{billingPortalState.error}</p>}
    </section>

    {renderCheckoutCatalog(true, redesignedBillingState === 'free')}

    {redesignedBillingState === 'healthy-active' && subscriptionActionAvailable && <section className="rl-billing-active__section rl-billing-active__section--cancel" aria-labelledby="billing-active-cancel-title" data-subscription-cancellation-action="schedule">
      <h3 className="rl-billing-active__section-bar" id="billing-active-cancel-title">CANCEL YOUR PLAN</h3>
      <button type="button" className="rl-billing-active__cancel-action" onClick={requestSubscriptionCancellationChange} disabled={subscriptionMutationBusy}>Cancel subscription</button>
      {subscriptionMutationState.status === 'pending' && subscriptionMutationState.workspaceId === settingsWorkspaceId && <p className="rl-settings-note" role="status">Updating subscription...</p>}
      {subscriptionMutationState.status === 'error' && subscriptionMutationState.workspaceId === settingsWorkspaceId && !subscriptionConfirmation && <p className="rl-settings-note" role="alert">{subscriptionMutationState.error}</p>}
    </section>}
  </div>;

  const renderBillingReadState = () => <div className="rl-settings-card rl-billing-active" data-settings-panel="billing" data-billing-state={billingReadLoading ? 'loading' : 'error'}>
    <div className="rl-billing-active__head">
      <h2>Billing & credits</h2>
      <p>Manage your workspace subscription, billing, and payment details</p>
    </div>
    <CheckoutReturnNotice state={checkoutReturnState} onRetry={retryCheckoutReturn} onGoHome={goHomeAfterCheckout} />
    {renderSubscriptionConfirmationNotice()}
    {commercialState && commercialState.status === 'unauthorized'
        ? <p className="rl-settings-note" role="alert">{commercialPresentation.note}</p>
        : <div className="rl-checkout-unavailable" role="alert">
            <div>
              <h3>Plans are unavailable</h3>
              <p>We could not load the current billing catalog. No guessed pricing is shown.</p>
            </div>
            <button type="button" className="rl-btn rl-btn--secondary" onClick={retryCheckoutCatalog} disabled={checkoutState.status === 'catalog_loading'}>
              {checkoutState.status === 'catalog_loading' ? 'Loading plans...' : 'Try again'}
            </button>
          </div>}
  </div>;
  const renderBilling = () => !workspaceAdmin ? renderCredits() : billingReadLoading ? null : !billingReadReady ? renderBillingReadState() : redesignedBilling ? renderRedesignedBilling() :
  <div className="rl-settings-card" data-settings-panel="billing">
      <div className="rl-settings-card__head">
        <div>
          <h2>Billing & credits</h2>
          <p>Review this Workspace subscription and article usage.</p>
        </div>
        {currentSubscriptionPresent && <button type="button" className="rl-btn rl-btn--secondary" onClick={handleManageBilling} disabled={billingPortalState.status === 'loading'}>
          {billingPortalState.status === 'loading' ? 'Opening billing...' : 'Manage billing'}
        </button>}
      </div>
      <CheckoutReturnNotice state={checkoutReturnState} onRetry={retryCheckoutReturn} onGoHome={goHomeAfterCheckout} />
      {renderSubscriptionConfirmationNotice()}
      {commercialState && commercialState.status === 'error'
        ? <div className="rl-checkout-unavailable" role="alert">
            <div>
              <h3>Plans are unavailable</h3>
              <p>We could not load the current billing catalog. No guessed pricing is shown.</p>
            </div>
            <button type="button" className="rl-btn rl-btn--secondary" onClick={retryCheckoutCatalog} disabled={checkoutState.status === 'catalog_loading'}>
              {checkoutState.status === 'catalog_loading' ? 'Loading plans...' : 'Try again'}
            </button>
          </div>
        : commercialState && commercialState.status === 'loaded' && !currentSubscriptionPresent
        ? renderCheckoutCatalog()
        : <React.Fragment>
          <div className="rl-settings-billing-grid">
            <div className="rl-settings-metric">
              <span>Current plan</span>
              <strong>{commercialPresentation.plan}</strong>
            </div>
            <div className="rl-settings-metric">
              <span>Payment status</span>
              <strong>{commercialPresentation.paymentStatus}</strong>
            </div>
            <div className="rl-settings-metric">
              <span>Current billing cycle</span>
              <strong>{commercialPresentation.billingCycle}</strong>
            </div>
            <div className="rl-settings-metric">
              <span>Billing cadence</span>
              <strong>{commercialPresentation.cadence}</strong>
            </div>
            <div className="rl-settings-metric">
              <span>Cancellation</span>
              <strong>{commercialPresentation.cancellation}</strong>
            </div>
            <div className="rl-settings-metric">
              <span>Seats</span>
              <strong>{commercialPresentation.seats}</strong>
            </div>
          </div>
          {billingPortalState.error && <p className="rl-settings-note" role="alert">{billingPortalState.error}</p>}
          {commercialPresentation.note && <p className="rl-settings-note" role={commercialState && ['error', 'unauthorized'].includes(commercialState.status) ? 'alert' : 'status'}>{commercialPresentation.note}</p>}
          {subscriptionActionAvailable && <div className="rl-settings-usage" data-subscription-cancellation-action={subscriptionCancellationScheduled ? 'keep' : 'schedule'}>
            <div>
              <h3>Subscription</h3>
              <p>{subscriptionCancellationScheduled ? `Cancellation is scheduled for ${subscriptionPeriodEndLabel}. You can keep this subscription and its next renewal.` : `Your current subscription remains active through ${subscriptionPeriodEndLabel}.`}</p>
            </div>
            <button type="button" className="rl-btn rl-btn--secondary" onClick={requestSubscriptionCancellationChange} disabled={subscriptionMutationBusy}>
              {subscriptionCancellationScheduled ? 'Keep subscription' : 'Cancel subscription'}
            </button>
          </div>}
          {subscriptionMutationState.status === 'error' && subscriptionMutationState.workspaceId === settingsWorkspaceId && !subscriptionConfirmation && <p className="rl-settings-note" role="alert">{subscriptionMutationState.error}</p>}
        </React.Fragment>}
      <div className="rl-settings-usage rl-settings-usage--credits">
        <div>
          <h3>Article credits</h3>
          <p>Credit totals are loaded separately from the Workspace credit service.</p>
        </div>
      </div>
      <div className="rl-settings-billing-grid">
        <div className="rl-settings-metric">
          <span>Total credits</span>
          <strong>{creditTotalText}</strong>
        </div>
        <div className="rl-settings-metric">
          <span>Consumed credits</span>
          <strong>{creditConsumedText}</strong>
        </div>
        <div className="rl-settings-metric">
          <span>Credits remaining</span>
          <strong>{creditRemainingText}</strong>
        </div>
      </div>
      {creditStateMessage && <p className="rl-settings-note" role={creditState && creditState.status === 'error' ? 'alert' : 'status'}>{creditStateMessage}</p>}
      {commercialState && commercialState.status === 'loaded' && currentSubscriptionPresent && renderCheckoutCatalog()}
    </div>;

  const renderSupport = () =>
  <div className="rl-settings-card">
      <div className="rl-settings-card__head">
        <div>
          <h2>Support</h2>
          <p>Find help, contact the team, or share product feedback.</p>
        </div>
      </div>
      <div className="rl-settings-support-grid">
        <div className="rl-settings-support-card">
          <h3>Help center</h3>
          <p>Help documentation is not connected yet.</p>
          <button type="button" className="rl-btn rl-btn--secondary" disabled title="Help center is coming soon.">Open help</button>
        </div>
        <div className="rl-settings-support-card">
          <h3>Contact support</h3>
          <p>Support contact routing is not connected yet.</p>
          <button type="button" className="rl-btn rl-btn--secondary" disabled title="Support contact is coming soon.">Contact us</button>
        </div>
        <div className="rl-settings-support-card">
          <h3>Report a bug</h3>
          <p>Bug reporting will be available soon.</p>
          <button type="button" className="rl-btn rl-btn--secondary" disabled title="Bug reports are coming soon.">Report bug</button>
        </div>
        <div className="rl-settings-support-card">
          <h3>Share feedback</h3>
          <p>Product feedback routing is not connected yet.</p>
          <button type="button" className="rl-btn rl-btn--secondary" disabled title="Feedback is coming soon.">Send feedback</button>
        </div>
      </div>
    </div>;

  const renderSoon = () =>
  <div className="rl-settings-card rl-settings-card--soon">
      <div className="rl-settings-soon">
        <div className="rl-settings-soon__icon" aria-hidden="true"></div>
        <h2>{activeSection.label}</h2>
        <p>This section will be available soon.</p>
      </div>
    </div>;

  return (
    <React.Fragment>
    {selectedSectionId && <main className='rl-page rl-settings'>
      <div className='rl-page__inner rl-settings__inner'>
        <div className='rl-settings__head'>
          <h1>Settings</h1>
          <p>Manage your profile, workspace, billing &amp; credits, and support.</p>
        </div>
        <div className='rl-settings-tabs-wrap'>
          <nav className='rl-settings-tabs' aria-label='Settings sections' role='tablist'>
            {settingsSections.map((section, index) =>
            <button
              key={section.id}
              id={'settings-tab-' + section.id}
              type='button'
              role='tab'
              aria-selected={selectedSectionId === section.id}
              aria-controls={'settings-panel-' + section.id}
              className={'rl-settings-tabs__item ' + (selectedSectionId === section.id ? 'rl-settings-tabs__item--active' : '')}
              onClick={() => {setSelected(section.id);setSaved('');}}
              onKeyDown={(event) => handleSettingsTabKeyDown(event, index)}>
              {section.label}
            </button>
            )}
          </nav>
        </div>
        <div className='rl-settings__layout'>
          <section id={'settings-panel-' + selectedSectionId} className={'rl-settings__panel ' + (selectedSectionId === 'profile' ? 'rl-settings__panel--profile' : selectedSectionId === 'workspace' ? 'rl-settings__panel--workspace' : selectedSectionId === 'billing' ? 'rl-settings__panel--billing' : '')} role='tabpanel' aria-labelledby={'settings-tab-' + selectedSectionId} aria-live='polite'>
            {selectedSectionId === 'profile' ? renderProfile() :
            selectedSectionId === 'workspace' ? renderWorkspace() :
            selectedSectionId === 'billing' ? renderBilling() :
            selectedSectionId === 'support' ? renderSupport() :
            renderSoon()}
            {saved && <div className='rl-settings-saved' role='status'><span>{saved}</span></div>}
          </section>
        </div>
      </div>
    </main>}
    <WorkspaceInviteMemberDialog open={workspaceInviteDialogOpen} growthDisabled={!workspaceCanGrowTeam} form={workspaceInviteForm} emailInputRef={workspaceInviteEmailRef} onEmailChange={updateWorkspaceInviteEmail} onRoleChange={updateWorkspaceInviteRole} onCancel={closeWorkspaceInviteDialog} onSubmit={submitWorkspaceInvitation} />
    <WorkspaceInvitationCancelDialog invitation={workspaceCancelInvitation} busy={workspaceCancelInvitationBusy} error={workspaceCancelInvitationError} onCancel={closeWorkspaceCancelInvitation} onConfirm={confirmWorkspaceCancelInvitation} />
    <WorkspaceRemoveMemberDialog member={workspaceRemoveMember} busy={workspaceRemoveMemberBusy} error={workspaceRemoveMemberError} onCancel={closeWorkspaceRemoveMember} onConfirm={confirmWorkspaceRemoveMember} />
    <SubscriptionCancellationDialog
      flow={workspaceAdmin && (subscriptionActionAvailable || subscriptionMutationBusy) ? subscriptionConfirmation : null}
      busy={subscriptionMutationState.status === 'submitting'}
      error={subscriptionConfirmation && subscriptionMutationState.status === 'error' ? subscriptionMutationState.error : ''}
      onClose={closeSubscriptionConfirmation}
      onBack={() => updateSubscriptionFlow({ step: subscriptionConfirmation.step === 'reason' ? 'step1' : 'reason', validation: '' })}
      onContinue={() => updateSubscriptionFlow({ step: 'reason', validation: '' })}
      onReasonChange={(reason) => updateSubscriptionFlow({ reason, validation: '', secondChanceDeclined: subscriptionConfirmation.secondChanceDeclined })}
      onCommentChange={(comment) => updateSubscriptionFlow({ comment, validation: '' })}
      onReasonContinue={continueCancellationReason}
      onAcceptRetention={acceptRetentionOffer}
      onDeclineSecondChance={() => updateSubscriptionFlow({ step: 'final_confirm', secondChanceDeclined: true })}
      onConfirmCancellation={confirmFinalCancellation}
      onConfirmReverse={confirmCancellationReversal} />
    <SubscriptionUpgradeDialog
      flow={workspaceAdmin ? upgradeConfirmation : null}
      onClose={closeUpgradeConfirmation}
      onConfirm={runUpgradeConfirmation}
      onRetry={runUpgradeConfirmation}
      onManageBilling={() => handleManageBilling(true)} />
    <AccountPasswordDialog open={passwordDialogOpen} passwordEnabled={securityPasswordEnabled} onClose={() => setPasswordDialogOpen(false)} onSubmit={submitPasswordChange} />
    <AccountSessionsDialog open={sessionsDialogOpen} sessionsState={sessionsState} onClose={() => { setSessionsDialogOpen(false); setSessionConfirmation(null); }} onRequestSignOut={requestSessionSignOut} onRequestSignOutAll={requestSignOutAllOtherSessions} />
    <AccountSessionConfirmDialog request={sessionConfirmation} busy={sessionActionBusy} onCancel={() => setSessionConfirmation(null)} onConfirm={confirmSessionAction} />
    <AccountMfaDialog open={mfaDialogOpen} accountSecurity={accountSecurity} runSensitiveAction={runSensitiveAccountAction} onClose={() => setMfaDialogOpen(false)} onSecurityState={applyAccountSecurityState} onNotice={handleMfaNotice} onError={handleMfaError} onRequestRemove={requestMfaRemoval} />
    <AccountMfaRemoveDialog open={mfaRemoveOpen} busy={mfaRemoveBusy} error={mfaRemoveError} onCancel={cancelMfaRemoval} onConfirm={confirmMfaRemoval} />
    <AccountReverificationDialog request={reverificationRequest} onCancel={cancelNativeReverification} onComplete={completeNativeReverification} />
    </React.Fragment>);
}

/* ------------------------------------------------------------------ */
/* App shell */
function useCloudArticleCollection(aggregate = false) {
  const [state, setState] = useState({ status: 'loading', articles: [], error: '' });
  const [retryToken, setRetryToken] = useState(0);
  const requestRef = useRef(0);

  useEffect(() => {
    let mounted = true;
    const requestId = ++requestRef.current;
    const library = getCloudArticleLibrary();
    const controller = library && typeof library.createCollectionController === 'function' ?
      library.createCollectionController() : null;

    setState({ status: 'loading', articles: [], error: '' });

    if (!controller) {
      setState({ status: 'error', articles: [], error: 'Articles are unavailable right now.' });
    } else {
      controller.load({ cloudClient: window.RankLyxCloudArticles, ...(aggregate ? {view:'aggregate'} : {}) }).then((result) => {
        if (!mounted || requestId !== requestRef.current || result && result.stale) return;
        if (!result || result.ok !== true) {
          const error = result && result.error || {};
          setState({ status: 'error', articles: [], error: error.publicMessage || error.message || 'Articles are unavailable right now.' });
          return;
        }
        setState({ status: 'ready', articles: result.articles || [], error: '' });
      });
    }

    const handleWorkspaceSwitching = () => {
      requestRef.current += 1;
      if (controller) controller.dispose();
      if (mounted) setState({ status: 'loading', articles: [], error: '' });
    };
    const handleWebsiteChange = () => { handleWorkspaceSwitching(); setRetryToken((value) => value + 1); };
    window.addEventListener('ranklyx:workspace-switching', handleWorkspaceSwitching);
    window.addEventListener('clicklyx:website-context-changed', handleWebsiteChange);
    return () => {
      mounted = false;
      requestRef.current += 1;
      window.removeEventListener('ranklyx:workspace-switching', handleWorkspaceSwitching);
      window.removeEventListener('clicklyx:website-context-changed', handleWebsiteChange);
      if (controller) controller.dispose();
    };
  }, [retryToken, aggregate]);

  return {
    ...state,
    retry: () => setRetryToken((value) => value + 1)
  };
}

// Retain each Website's mounted form state in this document. An inactive form
// is hidden and its existing access hook prevents actions in another scope.
function WebsiteKnowledgeSurface({ children }) {
  const scope = window.ClicklyxWebsiteContext;
  const familyKey = () => {
    const state = scope && scope.inspect();
    if (!state) return 'legacy';
    const child = !state.mode || state.mode === 'legacy' ? 'legacy' : state.websiteId;
    return child ? JSON.stringify([state.userId, state.sessionId, state.workspaceId, child]) : '';
  };
  const [family, setFamily] = useState(familyKey);
  const [families, setFamilies] = useState(() => family ? [family] : []);
  useEffect(() => scope ? scope.subscribe(() => {
    const next = familyKey();
    setFamily(next);
    setFamilies((current) => next && !current.includes(next) ? [...current, next] : current);
  }) : undefined, []);
  return families.map((id) => <div key={id} style={{ display: id === family ? 'contents' : 'none' }}>{children}</div>);
}

function App() {
  const c5Enabled = !!(window.ClicklyxWebsites && window.ClicklyxWebsites.enabled === true);
  const websiteExperience = window.ClicklyxWebsitesUI.useWebsites(c5Enabled);
  const knowledgePages = window.ClicklyxWebsitesUI.useKnowledgePages(c5Enabled);
  const initialCheckoutReturn = getCapturedCheckoutReturn();
  const initialPaymentMethodReturn = new URLSearchParams(window.location.search).get('billing_payment_update') === 'returned';
  const initialCloudArticleRoute = (() => {
    try {
      const WF = window.RankLyxArticleWorkflow;
      if (WF && typeof WF.readCloudArticleRoute === 'function') {
        return WF.readCloudArticleRoute(window.location, window.RankLyxCloudArticles);
      }
    } catch (e) {}
    return { rawArticleId: '', articleId: '', valid: false };
  })();
  // Dashboard is the default landing view on a fresh session. The last-viewed
  // page is persisted so a refresh keeps the user on whatever page they're on.
  const [active, setActive] = useState(() => {
    if (initialCheckoutReturn || initialPaymentMethodReturn) return 'settings';
    if (initialCloudArticleRoute.rawArticleId) return 'ai-writer';
    try {
      const saved = localStorage.getItem('rl-active-nav');
      return ['websites','website-knowledge'].includes(saved) ? 'dashboard' : saved || 'dashboard';
    } catch (e) {
      return 'dashboard';
    }
  });
  useEffect(() => {
    try {
      if (!['websites','website-knowledge'].includes(active)) localStorage.setItem('rl-active-nav', active);
    } catch (e) {}
  }, [active]);

  // Brief prefill payload handed over when a calendar card's "Start Brief" button
  // is clicked. The token makes each hand-off distinct so BriefScreen re-applies
  // it even when the same card is started twice.
  const [briefPrefill, setBriefPrefill] = useState(null);
  const [writerSessionKey, setWriterSessionKey] = useState(0);
  const [userProfile, setUserProfile] = useState(loadProfileSettings);
  const [workspaceSettings, setWorkspaceSettings] = useState(loadWorkspaceSettings);
  const [checkoutReturn, setCheckoutReturn] = useState(() => initialCheckoutReturn ? {
    ...initialCheckoutReturn,
    workspaceId: getWorkspaceDirectoryId(workspaceSettings)
  } : null);
  const workspaceCommercialReads = useWorkspaceCommercialReads(workspaceSettings);
  const [settingsSectionRequest, setSettingsSectionRequest] = useState(() => initialCheckoutReturn || initialPaymentMethodReturn
    ? { section: 'billing', token: Date.now() }
    : loadSettingsSectionNavigationRequest());
  const [briefKnowledgeReturn, setBriefKnowledgeReturn] = useState(null);
  const [briefRestoreRequest, setBriefRestoreRequest] = useState(null);
  const [knowledgeSelectionRequest, setKnowledgeSelectionRequest] = useState(null);
  const articleCollection = useCloudArticleCollection(c5Enabled);
  const workspaceAccess = useWorkspaceAccessUi();
  const workspaceNoticeRole = workspaceAccess.workspaceId === getWorkspaceDirectoryId(workspaceSettings) ? workspaceSettings.role : '';
  const [writerWorkflow, setWriterWorkflow] = useState(() => initialCloudArticleRoute.rawArticleId ? {
    kind: 'cloud',
    articleId: initialCloudArticleRoute.articleId || initialCloudArticleRoute.rawArticleId,
    token: Date.now(),
    source: 'route'
  } : {
    kind: 'new-cloud',
    token: Date.now(),
    source: 'initial'
  });
  const clearCloudArticleRoute = () => {
    try {
      const WF = window.RankLyxArticleWorkflow;
      if (WF && typeof WF.writeCloudArticleRoute === 'function') WF.writeCloudArticleRoute('');
    } catch (e) {}
  };
  const startNewArticle = () => {
    if (!workspaceAccess.canStartArticleWorkflow) return false;
    const scope = window.ClicklyxWebsiteContext;
    if (!c5Enabled && scope && !scope.allows()) return false;
    const token = Date.now();
    clearCloudArticleRoute();
    setBriefKnowledgeReturn(null);
    setBriefRestoreRequest(null);
    setKnowledgeSelectionRequest(null);
    setWriterWorkflow({ kind: 'new-cloud', token, source: 'new-article' });
    setBriefPrefill({ token });
    setWriterSessionKey(token);
    setActive('ai-writer');
    return true;
  };
  const handleNavigate = (target, options) => {
    if (target === 'websites' || target === 'website-knowledge') {
      if (!c5Enabled) return;
      knowledgePages.close(); clearCloudArticleRoute(); setActive(target);
      const url = new URL(window.location.href);
      url.searchParams.delete('knowledgeWebsiteId'); url.searchParams.delete('websiteView');
      if (target === 'website-knowledge' && options && options.websiteId) {
        url.searchParams.set('knowledgeWebsiteId', options.websiteId);
        knowledgePages.open(options.websiteId, options.success, options.details);
      } else url.searchParams.set('websiteView', 'all');
      window.history.pushState(null, '', url.pathname + url.search + url.hash);
      return;
    }
    if (c5Enabled) {
      knowledgePages.close();
      const url = new URL(window.location.href);
      url.searchParams.delete('knowledgeWebsiteId'); url.searchParams.delete('websiteView');
      window.history.pushState(null, '', url.pathname + url.search + url.hash);
    }
    if (target === 'brief-return') {setActive('ai-writer'); return;}
    if (target === 'ai-writer') {
      const started = startNewArticle();
      if (started && checkoutReturn) setCheckoutReturn(null);
      return;
    }
    if (target === 'ai-chat' && !workspaceAccess.canUseAi) return;
    if (target !== 'settings' && checkoutReturn) setCheckoutReturn(null);
    if (target === 'settings' && options && options.section) {
      setSettingsSectionRequest({ section: options.section, token: Date.now() });
    }
    clearCloudArticleRoute();
    setBriefKnowledgeReturn(null);
    setActive(target);
  };
  useEffect(() => {
    if (!c5Enabled) return undefined;
    const route = () => {
      knowledgePages.close();
      const params = new URLSearchParams(window.location.search), id = params.get('knowledgeWebsiteId');
      if (id) {setActive('website-knowledge'); knowledgePages.open(id);}
      else if (params.get('websiteView') === 'all') setActive('websites');
      else setActive('dashboard');
    };
    route(); window.addEventListener('popstate', route);
    return () => window.removeEventListener('popstate', route);
  }, [c5Enabled]);
  const openKnowledgeFromBrief = (target, formSnapshot) => {
    const type = target === 'audience-icp' ? 'icp' : 'brand-voice';
    if (c5Enabled) {
      const websiteId = formSnapshot && formSnapshot.websiteId;
      if (!websiteId) return;
      const family = window.ClicklyxWebsites.briefFamily();
      const context = {source:'brief',type,target,websiteId,family,token:Date.now()};
      setBriefKnowledgeReturn(context);
      setBriefRestoreRequest({token:context.token,family,form:{...formSnapshot}});
      handleNavigate('website-knowledge',{websiteId,details:{tab:type === 'icp' ? 3 : 2,briefReturnContext:context}});
      return;
    }
    setBriefKnowledgeReturn({
      source: 'brief',
      type,
      target,
      token: Date.now()
    });
    setBriefRestoreRequest({
      token: Date.now(),
      form: { ...(formSnapshot || {}) }
    });
    setActive(target);
  };
  const returnToBriefFromKnowledge = (payload) => {
    if (c5Enabled) {
      if (!briefKnowledgeReturn || briefKnowledgeReturn.family !== window.ClicklyxWebsites.briefFamily()) return;
      setKnowledgeSelectionRequest({token:Date.now(),family:briefKnowledgeReturn.family});
      setBriefKnowledgeReturn(null);
      handleNavigate('brief-return');
      return;
    }
    const type = payload && payload.type || (briefKnowledgeReturn && briefKnowledgeReturn.type);
    setKnowledgeSelectionRequest({
      token: Date.now(),
      type,
      id: payload && payload.id || ''
    });
    setBriefKnowledgeReturn(null);
    setActive('ai-writer');
  };
  const openStoredArticle = (row) => {
    const article = row && (row.article || row);
    const library = getCloudArticleLibrary();
    const target = library && typeof library.resolveResumeTarget === 'function' ?
      library.resolveResumeTarget(article, {
        cloudClient: window.RankLyxCloudArticles,
        workflow: window.RankLyxArticleWorkflow
      }) : null;
    if (!target || target.ok !== true) {
      const error = target && target.error || {};
      window.alert(error.publicMessage || error.message || 'This Article could not be opened.');
      return;
    }
    if (target.kind === 'editor') {
      window.location.href = target.href;
      return;
    }
    const token = Date.now();
    try {
      const WF = window.RankLyxArticleWorkflow;
      if (WF && typeof WF.writeCloudArticleRoute === 'function') WF.writeCloudArticleRoute(target.articleId);
    } catch (e) {}
    setWriterWorkflow({ kind: 'cloud', articleId: target.articleId, token, source: 'articles' });
    setBriefPrefill(null);
    setWriterSessionKey(token);
    setActive('ai-writer');
  };
  const startBriefFromCard = (fields) => {
    if (!workspaceAccess.allows('canMutateWorkspaceContent') || !workspaceAccess.allows('canUseAi')) return false;
    const scope = typeof window !== 'undefined' && window.ClicklyxWebsiteContext;
    if (scope && ((!c5Enabled && !scope.allows()) || fields.requestOrigin && !scope.isCurrent(fields.requestOrigin))) return false;
    const token = Date.now();
    clearCloudArticleRoute();
    setBriefKnowledgeReturn(null);
    setBriefRestoreRequest(null);
    setKnowledgeSelectionRequest(null);
    setWriterWorkflow({ kind: 'new-cloud', token, source: 'card-prefill' });
    setBriefPrefill({ ...fields, token });
    setWriterSessionKey(token);
    setActive('ai-writer');
  };
  const BrandProfile = window.BrandProfile;
  const ProductKnowledge = window.ProductKnowledge;
  const AudienceIcp = window.IcpKnowledge;
  const BrandVoice = window.BrandVoice;
  return (
    <div className={`rl-app${c5Enabled && ['websites','website-knowledge'].includes(active) ? ' c5-active' : ''}`}>
      <Sidebar active={active} onNavigate={handleNavigate} user={userProfile} workspace={workspaceSettings} creditState={workspaceCommercialReads.creditState} workspaceAccess={workspaceAccess} websites={c5Enabled ? websiteExperience.state : null} websiteId={knowledgePages.websiteId} />
      <div className="rl-workspace">
        <TopBar active={active} onNavigate={handleNavigate} workspaceAccess={workspaceAccess} />
        {(active === 'dashboard' || active === 'articles' || active === 'ai-writer') && <WorkspaceAccessNotice access={workspaceAccess} role={workspaceNoticeRole} onNavigate={handleNavigate} />}
        {['calendar', 'settings', 'brand-profile', 'product-knowledge', 'audience-icp', 'brand-voice'].includes(active) && <WorkspaceAccessNotice access={workspaceAccess} role={workspaceNoticeRole} onNavigate={handleNavigate} />}
        <div style={{ display: active === 'dashboard' ? 'contents' : 'none' }}>
          <Dashboard websites={c5Enabled ? websiteExperience.state : null} onNavigate={handleNavigate} onOpenArticle={openStoredArticle} articleCollection={articleCollection} workspaceAccess={workspaceAccess} />
        </div>
        {c5Enabled && active === 'websites' && <window.ClicklyxWebsitesUI.WebsitesOverview state={websiteExperience.state} refresh={websiteExperience.refresh} onNavigate={handleNavigate} />}
        {c5Enabled && active === 'website-knowledge' && ['loading','error'].includes(knowledgePages.load.status) && <window.ClicklyxWebsitesUI.KnowledgeLoadState load={knowledgePages.load} onRetry={knowledgePages.retry} />}
        {c5Enabled && knowledgePages.pages.map(page => {
          const current = active === 'website-knowledge' && knowledgePages.websiteId === page.site.id && window.ClicklyxWebsiteContext.isCurrent(page.origin);
          return <div key={page.family} style={{display:current ? 'contents' : 'none'}}><window.ClicklyxWebsitesUI.KnowledgePage site={page.site} origin={current ? page.origin : null} success={page.success} details={page.details} onReturnToBrief={returnToBriefFromKnowledge} websites={websiteExperience.state} onNavigate={handleNavigate} /></div>;
        })}
        <div style={{ display: active === 'calendar' ? 'contents' : 'none' }}>
          <CalendarPage workspaceId={getWorkspaceDirectoryId(workspaceSettings)} key={getWorkspaceDirectoryId(workspaceSettings)} onStartBrief={startBriefFromCard} />
        </div>
        <div style={{ display: active === 'articles' ? 'contents' : 'none' }}>
          <ArticlesPage onCreateArticle={startNewArticle} onOpenArticle={openStoredArticle} articleCollection={articleCollection} workspaceAccess={workspaceAccess} websites={c5Enabled ? websiteExperience.state : null} />
        </div>
        <div style={{ display: active === 'settings' ? 'contents' : 'none' }}>
          <SettingsPage key={getWorkspaceDirectoryId(workspaceSettings)} user={userProfile} workspace={workspaceSettings} creditState={workspaceCommercialReads.creditState} commercialState={workspaceCommercialReads.commercialState} refreshCommercial={workspaceCommercialReads.refreshCommercial} refreshWorkspaceReads={workspaceCommercialReads.refreshWorkspaceReads} checkoutReturn={checkoutReturn} requestedSection={settingsSectionRequest} onNavigate={handleNavigate} onSaveProfile={setUserProfile} onSaveWorkspace={setWorkspaceSettings} onUpgradeComplete={(workspaceId) => {
            if (getWorkspaceDirectoryId(window.currentWorkspace || workspaceSettings) === workspaceId) articleCollection.retry();
          }} />
        </div>
        <div style={{ display: active === 'brand-profile' ? 'contents' : 'none' }}>
          <WebsiteKnowledgeSurface>{BrandProfile && <BrandProfile />}</WebsiteKnowledgeSurface>
        </div>
        <div style={{ display: active === 'product-knowledge' ? 'contents' : 'none' }}>
          <WebsiteKnowledgeSurface>{ProductKnowledge && <ProductKnowledge />}</WebsiteKnowledgeSurface>
        </div>
        <div style={{ display: active === 'audience-icp' ? 'contents' : 'none' }}>
          <WebsiteKnowledgeSurface>{AudienceIcp && <AudienceIcp briefReturnContext={briefKnowledgeReturn && briefKnowledgeReturn.target === 'audience-icp' ? briefKnowledgeReturn : null} onReturnToBrief={returnToBriefFromKnowledge} />}</WebsiteKnowledgeSurface>
        </div>
        <div style={{ display: active === 'brand-voice' ? 'contents' : 'none' }}>
          <WebsiteKnowledgeSurface>{BrandVoice && <BrandVoice briefReturnContext={briefKnowledgeReturn && briefKnowledgeReturn.target === 'brand-voice' ? briefKnowledgeReturn : null} onReturnToBrief={returnToBriefFromKnowledge} />}</WebsiteKnowledgeSurface>
        </div>
        <div style={{ display: active === 'websites' || active === 'website-knowledge' || active === 'dashboard' || active === 'calendar' || active === 'articles' || active === 'settings' || active === 'brand-profile' || active === 'product-knowledge' || active === 'audience-icp' || active === 'brand-voice' ? 'none' : 'contents' }}>
          <BriefScreen
            key={c5Enabled ? writerSessionKey + ':' + window.ClicklyxWebsites.briefFamily() : writerSessionKey}
            websites={c5Enabled ? websiteExperience.state : null}
            prefill={briefPrefill}
            workflow={writerWorkflow}
            onCreateKnowledge={openKnowledgeFromBrief}
            briefRestoreRequest={briefRestoreRequest}
            knowledgeSelectionRequest={knowledgeSelectionRequest}
            workspaceAccess={workspaceAccess}
            onSafeNavigate={handleNavigate} />
        </div>
      </div>
    </div>);

}

function renderRankLyxApp() {
  ReactDOM.createRoot(document.getElementById('root')).render(<App />);
}

if (window.RankLyxAuth && typeof window.RankLyxAuth.requirePrivatePage === 'function') {
  window.RankLyxAuth.requirePrivatePage().then(renderRankLyxApp);
} else {
  document.getElementById('root').innerHTML = '<main class="rl-auth-shell"><section class="rl-auth-card"><h1>Authentication unavailable</h1><p>The private workspace could not start.</p></section></main>';
}
