/** * ConnectAccountModal - OAuth account connection flow. */ import { useState } from '@wordpress/element'; import { __, sprintf } from '@wordpress/i18n'; import { TextControl, Spinner, Button } from '@aime/wp-components'; import useApi from '../../../hooks/useApi'; import { toast } from '../../common/Toast'; /** * Per-platform manual connection guide. */ const PLATFORM_GUIDE = { facebook: { color: '#1877F2', tokenLabel: __( 'Page Access Token or User Access Token', 'ai-marketing-expert' ), nameLabel: __( 'Page Name', 'ai-marketing-expert' ), namePlaceholder: __( 'Facebook page name', 'ai-marketing-expert' ), nameHelp: __( 'This is the page name label shown inside the plugin for the connected Facebook Page.', 'ai-marketing-expert' ), needsSecret: false, steps: [ { n: 1, text: __( 'Go to', 'ai-marketing-expert' ), link: { href: 'https://developers.facebook.com', label: 'developers.facebook.com' }, after: __( 'and log in with the account that manages your Page.', 'ai-marketing-expert' ) }, { n: 2, text: __( 'Create or open an App (type "Business"), then open', 'ai-marketing-expert' ), link: { href: 'https://developers.facebook.com/tools/explorer/', label: 'Graph API Explorer' }, after: __( 'and select your App from the top-right dropdown.', 'ai-marketing-expert' ) }, { n: 3, text: __( 'Click "Generate Access Token" and add permissions: pages_show_list, pages_manage_posts, and pages_read_engagement. Complete the login dialog.', 'ai-marketing-expert' ) }, { n: 4, text: __( 'If Graph API Explorer still shows "User Token", that is okay. The plugin can now resolve your Page automatically when the token can access only one Page.', 'ai-marketing-expert' ) }, { n: 5, text: __( 'If your token can access multiple Pages, run', 'ai-marketing-expert' ), link: { href: 'https://developers.facebook.com/tools/explorer/', label: '/me/accounts' }, after: __( 'in Graph API Explorer and copy the Page ID you want to connect.', 'ai-marketing-expert' ) }, { n: 6, text: __( 'You can still switch from "User Token" to your Page in Graph API Explorer to get a Page Access Token, then paste that token below.', 'ai-marketing-expert' ) }, ], }, instagram: { color: '#E4405F', tokenLabel: __( 'Instagram Access Token', 'ai-marketing-expert' ), nameLabel: __( 'Account Name', 'ai-marketing-expert' ), namePlaceholder: __( 'Instagram account name', 'ai-marketing-expert' ), nameHelp: __( 'This is the label shown inside the plugin for the connected Instagram account.', 'ai-marketing-expert' ), needsSecret: false, steps: [ { n: 1, text: __( 'Make sure your Instagram is a Professional account (Business or Creator). On Instagram: Profile → ☰ → Settings → Professional account.', 'ai-marketing-expert' ) }, { n: 2, text: __( 'Go to', 'ai-marketing-expert' ), link: { href: 'https://developers.facebook.com/apps', label: 'developers.facebook.com/apps' }, after: __( '→ create or open an App (type "Business").', 'ai-marketing-expert' ) }, { n: 3, text: __( 'In the left menu click "Add Product" → find "Instagram" → click "Set up" → choose "API setup with Instagram business login".', 'ai-marketing-expert' ) }, { n: 4, text: __( 'Scroll down in the Instagram setup page to find your account → click "Generate token" → log in when prompted. The token is already long-lived (60 days). No Facebook Page needed.', 'ai-marketing-expert' ) }, { n: 5, text: __( 'Copy the Access Token AND your Instagram User ID shown on the same page. Paste both in the fields below.', 'ai-marketing-expert' ) }, ], }, x: { color: '#000000', tokenLabel: __( 'Access Token', 'ai-marketing-expert' ), nameLabel: __( 'Account Name', 'ai-marketing-expert' ), namePlaceholder: __( 'X account name', 'ai-marketing-expert' ), nameHelp: __( 'This is the label shown inside the plugin for the connected X account.', 'ai-marketing-expert' ), needsSecret: true, needsAppCredentials: true, apiKeyLabel: __( 'API Key (Consumer Key)', 'ai-marketing-expert' ), apiSecretLabel: __( 'API Secret (Consumer Secret / Secret Key)', 'ai-marketing-expert' ), apiKeyHelp: __( 'In X docs this is also called the Consumer Key.', 'ai-marketing-expert' ), apiSecretHelp: __( 'In X docs this is also called the Consumer Secret or Secret Key.', 'ai-marketing-expert' ), bearerTokenHelp: __( 'Bearer Token is not required for this plugin. X posting here uses OAuth 1.0a user context with API Key, API Secret, Access Token, and Access Token Secret.', 'ai-marketing-expert' ), steps: [ { n: 1, isWarning: true, text: __( 'Notice: X.com (Twitter) API is NOT free. It is a premium/pay-as-you-go service and requires paid credits to publish posts.', 'ai-marketing-expert' ) }, { n: 2, text: __( 'Go to', 'ai-marketing-expert' ), link: { href: 'https://developer.twitter.com/en/portal/projects-and-apps', label: 'developer.twitter.com' }, after: __( 'and create a Project + App.', 'ai-marketing-expert' ) }, { n: 3, text: __( 'Under App Settings → "User authentication settings", set permissions to Read and Write.', 'ai-marketing-expert' ) }, { n: 4, text: __( 'Go to the "Keys and Tokens" tab of your App.', 'ai-marketing-expert' ) }, { n: 5, text: __( 'Copy your Consumer Key and Secret Key. In this plugin those map to API Key and API Secret.', 'ai-marketing-expert' ) }, { n: 6, text: __( 'Under Authentication Tokens, generate an Access Token and Access Token Secret.', 'ai-marketing-expert' ) }, { n: 7, text: __( 'You do not need the Bearer Token for this plugin. Paste only those four values in the fields below.', 'ai-marketing-expert' ) }, ], }, linkedin: { color: '#0A66C2', tokenLabel: __( 'LinkedIn Access Token', 'ai-marketing-expert' ), nameLabel: __( 'Account / Company Name', 'ai-marketing-expert' ), namePlaceholder: __( 'LinkedIn account or page name', 'ai-marketing-expert' ), nameHelp: __( 'This is the label shown inside the plugin for the connected LinkedIn profile or company page.', 'ai-marketing-expert' ), needsSecret: false, steps: [ { n: 1, text: __( 'Go to', 'ai-marketing-expert' ), link: { href: 'https://www.linkedin.com/developers/apps', label: 'linkedin.com/developers' }, after: __( 'and create an App (linked to your LinkedIn Page or Personal profile).', 'ai-marketing-expert' ) }, { n: 2, text: __( 'Under the Products tab, request access to "Share on LinkedIn" and "Sign In with LinkedIn using OpenID Connect".', 'ai-marketing-expert' ) }, { n: 3, text: __( 'Under the Auth tab, generate an OAuth 2.0 token with permissions (w_member_social or w_organization_social), or use the token tool.', 'ai-marketing-expert' ) }, { n: 4, text: __( 'Paste the Access Token below. The plugin will automatically detect your member or organization URN.', 'ai-marketing-expert' ) }, ], }, }; const GuideStep = ( { step } ) => (
  • { step.n } { step.text }{ ' ' } { step.link && ( { step.link.label } ) } { step.after && ' ' }{ step.after }
  • ); const pluginUrl = window.aimeData?.pluginUrl || ''; // Feature flag: Enable 1-Click OAuth for Meta (Facebook & Instagram). // Set to false while Meta App Review is pending so Facebook & Instagram use direct manual token setup. // Set to true once Meta approves the app to re-enable 1-Click Connect for Facebook & Instagram. const ENABLE_META_OAUTH = false; const platforms = [ { id: 'facebook', name: 'Facebook', color: '#1877F2', icon: pluginUrl + 'assets/img/facebook-logo.svg', description: __( 'Connect your Facebook Page to publish posts.', 'ai-marketing-expert' ), }, { id: 'instagram', name: 'Instagram', color: '#E4405F', icon: pluginUrl + 'assets/img/instagram-logo.svg', description: __( 'Connect Instagram Business to share photos & stories.', 'ai-marketing-expert' ), }, { id: 'x', name: 'X (Twitter)', color: '#000000', icon: pluginUrl + 'assets/img/x-logo.svg', description: __( 'Connect your X account to post tweets.', 'ai-marketing-expert' ), }, { id: 'linkedin', name: 'LinkedIn', color: '#0A66C2', icon: pluginUrl + 'assets/img/linkedin-logo.svg', description: __( 'Connect your LinkedIn Profile or Company Page to publish professional updates.', 'ai-marketing-expert' ), }, ]; const ConnectAccountModal = ( { account = null, onClose, onConnected } ) => { const { post, put, loading } = useApi(); const isEditing = !! account; const [ step, setStep ] = useState( isEditing ? 'manual' : 'choose' ); // choose, connecting, select_accounts, manual, instagram_prerequisites const [ selectedPlatform, setSelectedPlatform ] = useState( account?.platform || null ); const [ candidatesData, setCandidatesData ] = useState( null ); const [ selectedAccountIds, setSelectedAccountIds ] = useState( [] ); const [ savingSelected, setSavingSelected ] = useState( false ); const [ instagramConfirmed, setInstagramConfirmed ] = useState( false ); const [ manualData, setManualData ] = useState( { name: account?.name || '', api_key: '', api_secret: '', access_token: '', access_secret: '', platform_user_id: account?.platform_user_id || '', } ); const emptyManualData = { name: '', api_key: '', api_secret: '', access_token: '', access_secret: '', platform_user_id: '', }; const handleOAuthConnect = async ( platform ) => { setSelectedPlatform( platform ); setStep( 'connecting' ); try { const res = await post( '/social/accounts/connect', { platform } ); if ( res.url ) { const popup = window.open( res.url, 'aime_social_auth', 'width=600,height=700,scrollbars=yes' ); let messageHandled = false; const handleMessage = async ( event ) => { if ( messageHandled ) { return; } // Trust messages from own origin (bridge mode) or the OAuth proxy origin. const trustedOrigins = [ window.location.origin, 'https://oauth.wpthemespace.com', ]; if ( ! trustedOrigins.includes( event.origin ) ) { return; } if ( event.data?.type === 'aime_oauth_error' ) { messageHandled = true; window.removeEventListener( 'message', handleMessage ); if ( popup && ! popup.closed ) { try { popup.close(); } catch ( _ ) {} } toast( event.data.error || __( 'OAuth connection failed.', 'ai-marketing-expert' ), 'error' ); setStep( 'choose' ); return; } if ( event.data?.type !== 'aime_oauth_callback' ) { return; } messageHandled = true; window.removeEventListener( 'message', handleMessage ); if ( popup && ! popup.closed ) { try { popup.close(); } catch ( _ ) {} } try { const callbackRes = await post( '/social/accounts/callback', { // The provider may not echo `platform` back; fall back to the chosen one. platform: event.data.platform || platform, code: event.data.code, state: event.data.state, } ); if ( callbackRes?.requires_selection ) { setCandidatesData( callbackRes ); const avail = callbackRes.accounts.length; const initialSelected = []; let count = 0; for ( const acc of callbackRes.accounts ) { if ( ! acc.already_connected && count < avail ) { initialSelected.push( String( acc.id ) ); count++; } } setSelectedAccountIds( initialSelected ); setStep( 'select_accounts' ); return; } toast( callbackRes?.message || __( 'Account connected successfully!', 'ai-marketing-expert' ) ); onConnected(); } catch ( err ) { toast( err.message, 'error' ); setStep( 'choose' ); } }; window.addEventListener( 'message', handleMessage ); const timer = setInterval( () => { if ( popup && popup.closed ) { clearInterval( timer ); window.removeEventListener( 'message', handleMessage ); if ( ! messageHandled ) { setStep( 'choose' ); } } }, 1000 ); } else if ( res.message ) { toast( res.message, 'info' ); setStep( 'manual' ); } } catch ( e ) { toast( e.message, 'error' ); setStep( 'choose' ); } }; const handleAccountCheckboxToggle = ( id, canToggle ) => { setSelectedAccountIds( ( prev ) => { if ( prev.includes( id ) ) { return prev.filter( ( item ) => item !== id ); } if ( ! canToggle ) { return prev; } return [ ...prev, id ]; } ); }; const handleToggleSelectAll = () => { if ( ! candidatesData?.accounts ) return; const selectable = candidatesData.accounts.filter( ( a ) => ! a.already_connected ); if ( selectedAccountIds.length === selectable.length ) { setSelectedAccountIds( [] ); } else { setSelectedAccountIds( selectable.map( ( a ) => String( a.id ) ) ); } }; const handleSaveSelectedAccounts = async () => { if ( ! candidatesData?.session_id || ! selectedAccountIds.length ) return; setSavingSelected( true ); try { const res = await post( '/social/accounts/save-selected', { session_id: candidatesData.session_id, selected_ids: selectedAccountIds, } ); toast( res.message || __( 'Accounts connected successfully!', 'ai-marketing-expert' ) ); onConnected(); } catch ( err ) { toast( err.message, 'error' ); } finally { setSavingSelected( false ); } }; // Manual mode: go straight to manual connect form. const handlePlatformSelect = ( platform ) => { setSelectedPlatform( platform ); setStep( 'manual' ); }; const handleManualConnect = async () => { if ( ! manualData.name ) { toast( __( 'Name is required.', 'ai-marketing-expert' ), 'error' ); return; } if ( ! isEditing && ! manualData.access_token ) { toast( __( 'Name and access token are required.', 'ai-marketing-expert' ), 'error' ); return; } if ( ! isEditing && selectedPlatform === 'facebook' && ! manualData.access_token.trim() ) { toast( __( 'A Facebook access token is required.', 'ai-marketing-expert' ), 'error' ); return; } if ( ! isEditing && selectedPlatform === 'x' && ( ! manualData.api_key || ! manualData.api_secret || ! manualData.access_secret ) ) { toast( __( 'X API key, API secret, access token, and access token secret are required.', 'ai-marketing-expert' ), 'error' ); return; } try { const payload = { platform: selectedPlatform, name: manualData.name, api_key: manualData.api_key, api_secret: manualData.api_secret, access_token: manualData.access_token, access_secret: manualData.access_secret, platform_user_id: manualData.platform_user_id, }; if ( isEditing ) { await put( `/social/accounts/${ account.id }`, payload ); toast( __( 'Account updated successfully!', 'ai-marketing-expert' ) ); } else { await post( '/social/accounts/connect-manual', payload ); toast( __( 'Account connected successfully!', 'ai-marketing-expert' ) ); } onConnected(); } catch ( e ) { toast( e.message, 'error' ); } }; return (
    { if ( e.target === e.currentTarget ) onClose(); } }>

    { isEditing ? __( 'Edit Account', 'ai-marketing-expert' ) : ( step === 'instagram_prerequisites' ? __( 'Instagram Setup Guide', 'ai-marketing-expert' ) : __( 'Connect Account', 'ai-marketing-expert' ) ) }

    { step === 'choose' && (

    { __( 'Choose a platform to connect:', 'ai-marketing-expert' ) }

    { platforms.map( ( p ) => { const isOneClick = ( ( ENABLE_META_OAUTH && ( p.id === 'facebook' || p.id === 'instagram' ) ) || p.id === 'linkedin' ); return ( ); } ) }
    { __( 'Prefer entering API keys or access tokens manually?', 'ai-marketing-expert' ) }{ ' ' }
    ) } { step === 'instagram_prerequisites' && (
    Instagram

    { __( 'Connect Instagram Business Account', 'ai-marketing-expert' ) }

    { __( 'Meta (Facebook) requires 2 quick setup requirements before connecting:', 'ai-marketing-expert' ) }
    { /* Step 1 */ }
    1
    { __( 'Switch to Professional Account (Business or Creator)', 'ai-marketing-expert' ) }
    { __( 'Meta does not permit posting to Personal accounts. It is 100% free to switch.', 'ai-marketing-expert' ) }
    📱 { __( 'In Instagram App: Settings & privacy → Account type & tools → Switch to professional account.', 'ai-marketing-expert' ) }
    { /* Step 2 */ }
    2
    { __( 'Link Instagram to a Facebook Page', 'ai-marketing-expert' ) }
    { __( 'Your Instagram account must be connected to a Facebook Page where you are an Admin.', 'ai-marketing-expert' ) }
    🔗 { __( 'In Instagram App: Edit profile → Under "Public business information", tap Page → Connect your Facebook Page.', 'ai-marketing-expert' ) }
    { /* Tip */ }
    💡 { __( 'Tip during Meta popup login:', 'ai-marketing-expert' ) }{ ' ' } { __( 'Make sure to select BOTH your Facebook Page and Instagram Account. If you previously connected, click "Edit settings" in the popup to verify both are checked.', 'ai-marketing-expert' ) }
    { /* Confirmation Checkbox */ }
    { __( 'Prefer direct token setup without Facebook Page?', 'ai-marketing-expert' ) }{ ' ' }
    ) } { step === 'connecting' && (

    { sprintf( __( 'Connecting to %s…', 'ai-marketing-expert' ), selectedPlatform ? selectedPlatform.toUpperCase() : '' ) }

    { __( 'Please complete authorization in the popup window. This window will automatically finish once you approve.', 'ai-marketing-expert' ) }

    ) } { step === 'select_accounts' && candidatesData && (
    p.id === candidatesData.platform )?.icon } alt={ candidatesData.platform } style={ { width: 36, height: 36, objectFit: 'contain' } } />

    { candidatesData.platform === 'facebook' ? __( 'Select Facebook Pages', 'ai-marketing-expert' ) : __( 'Select Instagram Accounts', 'ai-marketing-expert' ) }

    { __( 'Select the accounts you want to connect.', 'ai-marketing-expert' ) }
    { candidatesData.accounts.length > 1 && (
    ) }
    { candidatesData.accounts.map( ( acc ) => { const isSelected = selectedAccountIds.includes( String( acc.id ) ); const isAlready = !! acc.already_connected; const canToggle = true; return (
    { if ( isAlready ) return; handleAccountCheckboxToggle( String( acc.id ), canToggle ); } } style={ { display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', borderRadius: 8, background: isSelected ? 'rgba(37, 99, 235, 0.05)' : 'var(--aime-bg, #fff)', border: `1px solid ${ isSelected ? '#3b82f6' : 'var(--aime-border, #e2e8f0)' }`, cursor: isAlready ? 'default' : ( canToggle ? 'pointer' : 'not-allowed' ), opacity: ( ! isAlready && ! isSelected && ! canToggle ) ? 0.5 : 1, transition: 'all 0.15s ease', } } > {} } style={ { width: 18, height: 18, cursor: isAlready ? 'default' : ( canToggle ? 'pointer' : 'not-allowed' ) } } /> { acc.avatar_url ? ( { ) : (
    { ( acc.name || '?' ).charAt( 0 ).toUpperCase() }
    ) }
    { acc.name }
    { acc.category && (
    { acc.category }
    ) }
    { isAlready && ( { __( 'Already Connected', 'ai-marketing-expert' ) } ) }
    ); } ) }
    ) } { step === 'manual' && ( () => { const guide = PLATFORM_GUIDE[ selectedPlatform ] || {}; const platformObj = platforms.find( ( p ) => p.id === selectedPlatform ); return (
    { /* Platform badge */ }
    { { platformObj?.name } { ! isEditing && ( )}
    { /* Step-by-step guide */ }

    { __( 'How to get your access token', 'ai-marketing-expert' ) }

      { ( guide.steps || [] ).map( ( s ) => ( ) ) }
    { /* Form fields */ } setManualData( { ...manualData, name: v } ) } placeholder={ guide.namePlaceholder || __( 'Enter an account name', 'ai-marketing-expert' ) } help={ guide.nameHelp || __( 'This is the label shown inside the plugin for the connected account.', 'ai-marketing-expert' ) } __nextHasNoMarginBottom /> { isEditing && (

    { __( 'Leave token and secret fields blank to keep the current saved values.', 'ai-marketing-expert' ) }

    )} { guide.needsAppCredentials && ( <>
    setManualData( { ...manualData, api_key: v } ) } placeholder={ __( 'Paste your X API key here', 'ai-marketing-expert' ) } help={ guide.apiKeyHelp } __nextHasNoMarginBottom />
    setManualData( { ...manualData, api_secret: v } ) } placeholder={ __( 'Paste your X API secret here', 'ai-marketing-expert' ) } type="password" help={ guide.apiSecretHelp } __nextHasNoMarginBottom />

    { guide.bearerTokenHelp }

    ) }
    setManualData( { ...manualData, access_token: v } ) } placeholder="Paste your access token here" __nextHasNoMarginBottom />
    { guide.needsSecret && (
    setManualData( { ...manualData, access_secret: v } ) } placeholder={ __( 'Paste your access token secret here', 'ai-marketing-expert' ) } help={ __( 'Required for X (Twitter) — found in Keys and Tokens tab.', 'ai-marketing-expert' ) } __nextHasNoMarginBottom />
    ) } { selectedPlatform === 'instagram' && (
    setManualData( { ...manualData, platform_user_id: v } ) } placeholder={ __( 'e.g. 17841400000000000', 'ai-marketing-expert' ) } help={ __( 'Found on App Dashboard → Instagram → API setup page, next to your account. Leave blank to auto-detect.', 'ai-marketing-expert' ) } __nextHasNoMarginBottom />
    ) } { selectedPlatform === 'facebook' && (
    setManualData( { ...manualData, platform_user_id: v } ) } placeholder={ __( 'Paste a Page ID if your token manages multiple Pages', 'ai-marketing-expert' ) } help={ __( 'Leave blank when the token belongs to one Page only. If you use a user token with multiple Pages, this field tells the plugin which Page to connect.', 'ai-marketing-expert' ) } __nextHasNoMarginBottom />
    ) }
    ); } )() }
    { step === 'instagram_prerequisites' && ( ) } { step === 'select_accounts' && ( ) } { step === 'manual' && ( ) }
    ); }; export default ConnectAccountModal;