# thinkrank/1.0.0/src/admin/components/essential-seo/IntegrationsTab.js

ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console &amp; Local SEO, version 1.0.0. 1,005 lines.

- Page: https://pluginprobe.com/plugins/thinkrank/1.0.0/code/src/admin/components/essential-seo/IntegrationsTab.js
- Raw: https://pluginprobe.com/plugins/thinkrank/1.0.0/raw/src/admin/components/essential-seo/IntegrationsTab.js
- Modified: 2025-08-10T07:57:44+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/thinkrank/1.0.0/code/src/admin/components/essential-seo/IntegrationsTab.js#L10-L20`.

```javascript
/**
 * Integrations Tab Component
 *
 * Centralized management for all external API integrations
 * Following DRY and KISS principles for clean, maintainable code
 *
 * @package ThinkRank
 * @since 1.0.0
 */

import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import {
    Card,
    CardBody,
    CardHeader,
    Spinner,
    Notice,
    TextControl,
    ToggleControl,
    Button,
    Flex,
    FlexItem,
    __experimentalText as Text
} from '@wordpress/components';
import apiFetch from '@wordpress/api-fetch';

/**
 * Get boolean settings list for integrations
 * Following schema settings pattern for consistent boolean handling
 */
const getBooleanIntegrationsSettings = () => [
    'ga4_auto_inject',
    'ga4_anonymize_ip',
    'ga4_exclude_admin',
    'ga4_tracking_verified',
    'auto_test_connections',
    'retry_failed_requests'
];

/**
 * Normalize integrations settings data types
 * Following schema settings pattern for consistent boolean handling
 */
const normalizeIntegrationsDataTypes = (settings) => {
    const normalized = { ...settings };

    // Convert boolean settings
    getBooleanIntegrationsSettings().forEach(key => {
        if (key in normalized) {
            normalized[key] = Boolean(normalized[key]);
        }
    });

    return normalized;
};

/**
 * Default integration settings
 * KISS: Simple, flat structure for Google API keys only
 */
const getDefaultIntegrationsSettings = () => ({
    // Google API Keys
    google_analytics_api_key: '',
    google_search_console_api_key: '',
    google_pagespeed_api_key: '',

    // GA4 Tracking Settings
    ga4_measurement_id: '',
    ga4_auto_inject: false,
    ga4_anonymize_ip: false,
    ga4_exclude_admin: false,
    ga4_tracking_verified: false,
    ga4_last_verification: '',

    // API Configuration
    api_timeout: 30,
    cache_duration: 3600,

    // Connection settings
    auto_test_connections: true,
    retry_failed_requests: true
});

/**
 * Default social media settings
 * DRY: Reuse existing social media settings structure
 */
const getDefaultSocialSettings = () => ({
    // Facebook settings
    facebook_app_id: '',
    facebook_admins: '',

    // Pinterest settings
    pinterest_site_verification: '',

    // Instagram settings
    instagram_verification: '',

    // TikTok settings
    tiktok_verification: '',

    // YouTube settings
    youtube_channel_id: '',

    // WhatsApp Business settings
    whatsapp_business_id: ''
});

/**
 * Integrations Tab Component
 * DRY: Reuses patterns from Analytics tab but simplified
 */
const IntegrationsTab = ({ activeSubSection = 'google-services' }) => {
    const [isLoading, setIsLoading] = useState(true);
    const [isSaving, setIsSaving] = useState(false);
    const [isTestingConnection, setIsTestingConnection] = useState(false);
    const [integrationsSettings, setIntegrationsSettings] = useState(getDefaultIntegrationsSettings());
    const [socialSettings, setSocialSettings] = useState(getDefaultSocialSettings());
    const [hasChanges, setHasChanges] = useState(false);
    const [notice, setNotice] = useState(null);
    const [connectionStatus, setConnectionStatus] = useState(null);

    // GA4 Tracking specific state
    const [conflicts, setConflicts] = useState([]);
    const [isCheckingConflicts, setIsCheckingConflicts] = useState(false);
    const [verificationResult, setVerificationResult] = useState(null);
    const [isVerifying, setIsVerifying] = useState(false);

    // Load settings on mount
    useEffect(() => {
        loadSettings();
    }, []);

    /**
     * Load integration settings
     * DRY: Reuses Settings Manager pattern for both categories
     */
    const loadSettings = async () => {
        try {
            setIsLoading(true);

            // Load integrations settings (Google API keys)
            const integrationsResponse = await apiFetch({
                path: '/thinkrank/v1/integrations/settings',
                method: 'GET'
            });

            // Load social platform settings (IDs and verification codes with selective encryption)
            const socialResponse = await apiFetch({
                path: '/thinkrank/v1/social-platforms/settings',
                method: 'GET'
            });

            if (integrationsResponse.success) {
                const loadedSettings = { ...getDefaultIntegrationsSettings(), ...integrationsResponse.data.settings };

                // Masked API keys (XXXX pattern) will be displayed in password fields
                // The save logic prevents these masked values from being sent back to the server

                // Normalize boolean values to ensure proper types
                const normalizedSettings = normalizeIntegrationsDataTypes(loadedSettings);
                setIntegrationsSettings(normalizedSettings);
            } else {
                setIntegrationsSettings(getDefaultIntegrationsSettings());
            }

            if (socialResponse.success) {
                const loadedSocialSettings = { ...getDefaultSocialSettings(), ...socialResponse.data.settings };

                // Masked verification codes (XXXX pattern) will be displayed in text fields
                // Public IDs (facebook_app_id, facebook_admins, youtube_channel_id, whatsapp_business_id) are not encrypted and show full values
                // Verification codes (pinterest_site_verification, instagram_verification, tiktok_verification) are encrypted and show masked values
                // The save logic prevents masked values from being sent back to the server

                setSocialSettings(loadedSocialSettings);
            } else {
                setSocialSettings(getDefaultSocialSettings());
            }
        } catch (error) {
            console.error('Failed to load integration settings:', error);
            setNotice({
                status: 'error',
                message: __('Failed to load integration settings. Please refresh the page.', 'thinkrank')
            });
        } finally {
            setIsLoading(false);
        }
    };

    /**
     * Handle integrations setting changes (Google API keys)
     * KISS: Simple state update pattern
     */
    const handleIntegrationsSettingChange = (key, value) => {
        setIntegrationsSettings(prev => ({ ...prev, [key]: value }));
        setHasChanges(true);
        setNotice(null);
    };

    /**
     * Handle social setting changes (Platform IDs and verification codes)
     * DRY: Same pattern as integrations settings
     */
    const handleSocialSettingChange = (key, value) => {
        setSocialSettings(prev => ({ ...prev, [key]: value }));
        setHasChanges(true);
        setNotice(null);
    };

    /**
     * Save settings for current active tab only
     * KISS: Only save the current tab's settings
     */
    const saveSettings = async () => {
        try {
            setIsSaving(true);
            setNotice(null);

            if (activeSubSection === 'google-services') {
                // Save Google Services (Integrations) settings only
                const integrationsData = { ...integrationsSettings };

                // Remove empty API keys and masked placeholders to avoid overwriting existing encrypted keys
                if (!integrationsData.google_analytics_api_key || !integrationsData.google_analytics_api_key.trim() || integrationsData.google_analytics_api_key.includes('XXXX')) {
                    delete integrationsData.google_analytics_api_key;
                }
                if (!integrationsData.google_search_console_api_key || !integrationsData.google_search_console_api_key.trim() || integrationsData.google_search_console_api_key.includes('XXXX')) {
                    delete integrationsData.google_search_console_api_key;
                }
                if (!integrationsData.google_pagespeed_api_key || !integrationsData.google_pagespeed_api_key.trim() || integrationsData.google_pagespeed_api_key.includes('XXXX')) {
                    delete integrationsData.google_pagespeed_api_key;
                }

                // Normalize boolean values before saving (following schema settings pattern)
                const normalizedIntegrationsData = normalizeIntegrationsDataTypes(integrationsData);

                const response = await apiFetch({
                    path: '/thinkrank/v1/integrations/settings',
                    method: 'POST',
                    data: { settings: normalizedIntegrationsData }
                });

                if (response.success) {
                    setHasChanges(false);
                    setNotice({
                        status: 'success',
                        message: __('Google Services settings saved successfully!', 'thinkrank')
                    });
                } else {
                    throw new Error('Failed to save Google Services settings');
                }

            } else if (activeSubSection === 'social-platforms') {
                // Save Social Platforms settings only
                const socialData = { ...socialSettings };

                // Remove empty verification codes to avoid overwriting existing encrypted codes
                if (!socialData.pinterest_site_verification?.trim()) {
                    delete socialData.pinterest_site_verification;
                }
                if (!socialData.instagram_verification?.trim()) {
                    delete socialData.instagram_verification;
                }
                if (!socialData.tiktok_verification?.trim()) {
                    delete socialData.tiktok_verification;
                }

                const response = await apiFetch({
                    path: '/thinkrank/v1/social-platforms/settings',
                    method: 'POST',
                    data: { settings: socialData }
                });

                if (response.success) {
                    setHasChanges(false);
                    setNotice({
                        status: 'success',
                        message: __('Social Platform settings saved successfully!', 'thinkrank')
                    });
                } else {
                    throw new Error('Failed to save Social Platform settings');
                }
            }

        } catch (error) {
            console.error('Save error:', error);
            setNotice({
                status: 'error',
                message: __('Failed to save settings. Please try again.', 'thinkrank')
            });
        } finally {
            setIsSaving(false);
        }
    };

    /**
     * Test API connections
     * DRY: Reuses connection testing pattern
     */
    const testConnections = async () => {
        try {
            setIsTestingConnection(true);
            setNotice(null);

            const response = await apiFetch({
                path: '/thinkrank/v1/integrations/test-connections',
                method: 'POST'
            });

            if (response.success) {
                setConnectionStatus(response.data);
                setNotice({
                    status: 'success',
                    message: __('Connection test completed successfully!', 'thinkrank')
                });
            } else {
                throw new Error(response.error || 'Connection test failed');
            }
        } catch (error) {
            console.error('Connection test error:', error);
            setNotice({
                status: 'error',
                message: __('Connection test failed. Please check your API keys.', 'thinkrank')
            });
        } finally {
            setIsTestingConnection(false);
        }
    };

    /**
     * Verify GA4 tracking
     * Following ThinkRank API patterns
     */
    const verifyTracking = async () => {
        if (!integrationsSettings.ga4_measurement_id) {
            setNotice({
                status: 'error',
                message: __('Please enter a GA4 Measurement ID first.', 'thinkrank')
            });
            return;
        }

        setIsVerifying(true);
        setVerificationResult(null);

        try {
            const response = await apiFetch({
                path: '/thinkrank/v1/integrations/verify-ga4-tracking',
                method: 'POST',
                data: {
                    measurement_id: integrationsSettings.ga4_measurement_id
                }
            });

            if (response.success) {
                setVerificationResult(response.data);

                // Update tracking settings if verification successful
                if (response.data.success) {
                    setIntegrationsSettings(prev => ({
                        ...prev,
                        ga4_tracking_verified: true,
                        ga4_last_verification: new Date().toLocaleString()
                    }));
                    setHasChanges(true);
                }
            }
        } catch (error) {
            setVerificationResult({
                success: false,
                message: __('Verification failed. Please try again.', 'thinkrank')
            });
        } finally {
            setIsVerifying(false);
        }
    };

    /**
     * Check for GA4 conflicts
     * Following ThinkRank API patterns
     */
    const checkConflicts = async () => {
        setIsCheckingConflicts(true);

        try {
            const response = await apiFetch({
                path: '/thinkrank/v1/integrations/detect-ga4-conflicts',
                method: 'GET'
            });

            if (response.success) {
                setConflicts(response.data.conflicts || []);
            }
        } catch (error) {
            console.error('Conflict detection failed:', error);
        } finally {
            setIsCheckingConflicts(false);
        }
    };

    // Check conflicts when measurement ID changes
    useEffect(() => {
        if (integrationsSettings.ga4_measurement_id) {
            checkConflicts();
        } else {
            setConflicts([]);
        }
    }, [integrationsSettings.ga4_measurement_id]);

    /**
     * Get tracking status indicator
     * Following ThinkRank status patterns
     */
    const getTrackingStatus = () => {
        if (!integrationsSettings.ga4_measurement_id) {
            return { status: 'inactive', label: __('Not Configured', 'thinkrank') };
        }

        if (integrationsSettings.ga4_tracking_verified) {
            return { status: 'active', label: __('Verified & Active', 'thinkrank') };
        }

        if (integrationsSettings.ga4_auto_inject) {
            return { status: 'pending', label: __('Configured (Not Verified)', 'thinkrank') };
        }

        return { status: 'manual', label: __('Manual Setup', 'thinkrank') };
    };

    /**
     * Render Google Services section
     * KISS: Clean, focused component
     */
    const renderGoogleServices = () => (
        <div className="thinkrank-tab-content">
            {/* Google Services Integration Workflow */}
            <Card size="small" className="thinkrank-mb-md">
                <CardBody>
                    <div style={{
                        padding: '12px',
                        backgroundColor: '#e8f5e8',
                        border: '1px solid #c8e6c8',
                        borderRadius: '4px',
                        marginBottom: '16px'
                    }}>
                        <h4 style={{ margin: '0 0 8px 0', color: '#2e7d32' }}>
                            {__('Google Services Integration', 'thinkrank')}
                        </h4>
                        <ol style={{ margin: '0', paddingLeft: '20px', color: '#2e7d32' }}>
                            <li>{__('Get API keys from Google Cloud Console', 'thinkrank')}</li>
                            <li>{__('Configure API keys below', 'thinkrank')}</li>
                            <li>{__('Enable real-time data fetching', 'thinkrank')}</li>
                            <li>{__('Monitor performance and analytics', 'thinkrank')}</li>
                        </ol>
                    </div>
                </CardBody>
            </Card>

            <div className="thinkrank-settings-grid">
                <Card size="small" className="thinkrank-mb-md">
                    <CardHeader>
                        <h3>{__('Google API Keys', 'thinkrank')}</h3>
                        <Text variant="muted">
                            {__('Configure API keys for Google services integration', 'thinkrank')}
                        </Text>
                    </CardHeader>
                    <CardBody>
                        <TextControl
                            label={__('Google Analytics Data API Key', 'thinkrank')}
                            value={integrationsSettings.google_analytics_api_key}
                            onChange={(value) => handleIntegrationsSettingChange('google_analytics_api_key', value)}
                            placeholder="AIzaSyD-9tSrke72PouQMnMX-a7UUAVNCKH6dsI"
                            help={
                                <>
                                    {__('Required for GA4 Analytics data retrieval. This will be encrypted and stored securely. ', 'thinkrank')}
                                    <a href="https://console.cloud.google.com/apis/library/analyticsdata.googleapis.com" target="_blank" rel="noopener noreferrer">
                                        {__('Enable Analytics Data API →', 'thinkrank')}
                                    </a>
                                    {__(' | ', 'thinkrank')}
                                    <a href="https://console.cloud.google.com/apis/credentials" target="_blank" rel="noopener noreferrer">
                                        {__('Create API Key →', 'thinkrank')}
                                    </a>
                                </>
                            }
                            type="text"
                            __next40pxDefaultSize={true}
                            __nextHasNoMarginBottom={true}
                            className="thinkrank-mb-sm"
                        />

                        <TextControl
                            label={__('Google Search Console API Key', 'thinkrank')}
                            value={integrationsSettings.google_search_console_api_key}
                            onChange={(value) => handleIntegrationsSettingChange('google_search_console_api_key', value)}
                            placeholder="AIzaSyB-1uEFiQPa4GX-LnQpVMz2E4KHrEEsB5Y"
                            help={
                                <>
                                    {__('Required for Search Console data and keyword rankings. This will be encrypted and stored securely. ', 'thinkrank')}
                                    <a href="https://console.cloud.google.com/apis/library/searchconsole.googleapis.com" target="_blank" rel="noopener noreferrer">
                                        {__('Enable Search Console API →', 'thinkrank')}
                                    </a>
                                    {__(' | ', 'thinkrank')}
                                    <a href="https://console.cloud.google.com/apis/credentials" target="_blank" rel="noopener noreferrer">
                                        {__('Create API Key →', 'thinkrank')}
                                    </a>
                                </>
                            }
                            type="text"
                            __next40pxDefaultSize={true}
                            __nextHasNoMarginBottom={true}
                            className="thinkrank-mb-sm"
                        />

                        <TextControl
                            label={__('Google PageSpeed Insights API Key', 'thinkrank')}
                            value={integrationsSettings.google_pagespeed_api_key}
                            onChange={(value) => handleIntegrationsSettingChange('google_pagespeed_api_key', value)}
                            placeholder="AIzaSyC-3vWFiQPa4GX-LnQpVMz2E4KHrEEsC6Z"
                            help={
                                <>
                                    {__('Required for Core Web Vitals and performance data. This will be encrypted and stored securely. ', 'thinkrank')}
                                    <a href="https://console.cloud.google.com/apis/library/pagespeedonline.googleapis.com" target="_blank" rel="noopener noreferrer">
                                        {__('Enable PageSpeed Insights API →', 'thinkrank')}
                                    </a>
                                    {__(' | ', 'thinkrank')}
                                    <a href="https://console.cloud.google.com/apis/credentials" target="_blank" rel="noopener noreferrer">
                                        {__('Create API Key →', 'thinkrank')}
                                    </a>
                                </>
                            }
                            type="text"
                            __next40pxDefaultSize={true}
                            __nextHasNoMarginBottom={true}
                        />
                    </CardBody>
                </Card>

                {/* Test Connection Button */}
                <Card size="small" className="thinkrank-mb-md">
                    <CardHeader>
                        <h3>{__('Connection Testing', 'thinkrank')}</h3>
                    </CardHeader>
                    <CardBody>
                        <Flex justify="space-between" align="center">
                            <FlexItem>
                                <Text>
                                    {__('Test your API connections to ensure everything is working correctly.', 'thinkrank')}
                                </Text>
                            </FlexItem>
                            <FlexItem>
                                <Button
                                    variant="secondary"
                                    onClick={testConnections}
                                    isBusy={isTestingConnection}
                                    disabled={isTestingConnection}
                                >
                                    {isTestingConnection ? __('Testing...', 'thinkrank') : __('Test Connections', 'thinkrank')}
                                </Button>
                            </FlexItem>
                        </Flex>
                    </CardBody>
                </Card>

                {/* Connection Status Display */}
                {connectionStatus && (
                    <Card size="small" className="thinkrank-mt-md thinkrank-mb-md">
                        <CardHeader>
                            <h3>{__('Connection Status', 'thinkrank')}</h3>
                        </CardHeader>
                        <CardBody>
                            <div className="thinkrank-space-y-4">
                                {Object.entries(connectionStatus).map(([service, status]) => (
                                    <Flex key={service} justify="space-between" align="center" className="thinkrank-py-2">
                                        <FlexItem>
                                            <Text>
                                                {service === 'google_analytics' ? __('Google Analytics', 'thinkrank') :
                                                 service === 'search_console' ? __('Search Console', 'thinkrank') :
                                                 service === 'pagespeed' ? __('PageSpeed', 'thinkrank') :
                                                 service.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())}
                                            </Text>
                                        </FlexItem>
                                        <FlexItem>
                                            <span className={`thinkrank-inline-flex thinkrank-items-center thinkrank-px-2 thinkrank-py-1 thinkrank-rounded thinkrank-text-xs thinkrank-font-medium thinkrank-border ${
                                                status.status === 'configured' ? 'thinkrank-bg-green thinkrank-bg-opacity-10 thinkrank-text-green thinkrank-border-green thinkrank-border-opacity-20' :
                                                status.status === 'error' ? 'thinkrank-bg-red thinkrank-bg-opacity-10 thinkrank-text-red thinkrank-border-red thinkrank-border-opacity-20' :
                                                'thinkrank-bg-gray-100 thinkrank-text-secondary thinkrank-border-light'
                                            }`}>
                                                {status.status === 'configured' ? __('Configured', 'thinkrank') :
                                                 status.status === 'error' ? __('Error', 'thinkrank') :
                                                 __('Not Configured', 'thinkrank')}
                                            </span>
                                        </FlexItem>
                                    </Flex>
                                ))}
                            </div>
                        </CardBody>
                    </Card>
                )}
            </div>

            {/* GA4 Tracking Management Card */}
            <Card size="small" className="thinkrank-mb-md">
                <CardHeader>
                    <h3>{__('Google Analytics Tracking', 'thinkrank')}</h3>
                    <Text variant="muted">
                        {__('Configure GA4 tracking code injection for your website', 'thinkrank')}
                    </Text>
                </CardHeader>
                <CardBody>
                    {/* Status Indicator */}
                    <div className="thinkrank-mb-md">
                        <Flex justify="space-between" align="center">
                            <FlexItem>
                                <Text>{__('Tracking Status:', 'thinkrank')}</Text>
                            </FlexItem>
                            <FlexItem>
                                {(() => {
                                    const status = getTrackingStatus();
                                    const statusConfig = {
                                        active: { color: 'green', icon: '✅' },
                                        pending: { color: 'orange', icon: '⏳' },
                                        manual: { color: 'blue', icon: '🔧' },
                                        inactive: { color: 'gray', icon: '⚪' }
                                    };
                                    const config = statusConfig[status.status] || statusConfig.inactive;

                                    return (
                                        <span className={`thinkrank-inline-flex thinkrank-items-center thinkrank-px-2 thinkrank-py-1 thinkrank-rounded thinkrank-text-xs thinkrank-font-medium thinkrank-border ${
                                            config.color === 'green' ? 'thinkrank-bg-green thinkrank-bg-opacity-10 thinkrank-text-green thinkrank-border-green thinkrank-border-opacity-20' :
                                            config.color === 'orange' ? 'thinkrank-bg-orange thinkrank-bg-opacity-10 thinkrank-text-orange thinkrank-border-orange thinkrank-border-opacity-20' :
                                            config.color === 'blue' ? 'thinkrank-bg-blue thinkrank-bg-opacity-10 thinkrank-text-blue thinkrank-border-blue thinkrank-border-opacity-20' :
                                            'thinkrank-bg-gray-100 thinkrank-text-secondary thinkrank-border-light'
                                        }`}>
                                            {config.icon} {status.label}
                                        </span>
                                    );
                                })()}
                                {isCheckingConflicts && <Spinner style={{ marginLeft: '10px' }} />}
                            </FlexItem>
                        </Flex>
                    </div>

                    {/* Measurement ID */}
                    <TextControl
                        label={__('GA4 Measurement ID', 'thinkrank')}
                        value={integrationsSettings.ga4_measurement_id}
                        onChange={(value) => handleIntegrationsSettingChange('ga4_measurement_id', value)}
                        placeholder="G-XXXXXXXXXX"
                        pattern="G-[A-Z0-9]{10}"
                        help={
                            <>
                                {__('Your GA4 Measurement ID from Google Analytics. ', 'thinkrank')}
                                <a href="https://support.google.com/analytics/answer/9539598" target="_blank" rel="noopener noreferrer">
                                    {__('Find your Measurement ID →', 'thinkrank')}
                                </a>
                            </>
                        }
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                        className="thinkrank-mb-sm"
                    />

                    {/* Conflict Warnings */}
                    {conflicts.length > 0 && (
                        <Notice status="warning" isDismissible={false} className="thinkrank-mb-sm">
                            <strong>{__('Potential Conflicts Detected:', 'thinkrank')}</strong>
                            <ul style={{ marginTop: '8px', marginBottom: '0' }}>
                                {conflicts.map((conflict, index) => (
                                    <li key={index}>
                                        <strong>{conflict.name}</strong>
                                        {conflict.type === 'plugin' && (
                                            <span> - {__('Consider disabling auto-inject to avoid duplicate tracking', 'thinkrank')}</span>
                                        )}
                                        {conflict.type === 'theme' && (
                                            <span> - {__('Manual GA4 detected in theme files', 'thinkrank')}</span>
                                        )}
                                    </li>
                                ))}
                            </ul>
                        </Notice>
                    )}

                    {/* Auto-inject Toggle */}
                    <ToggleControl
                        label={__('Auto-inject GA4 tracking code', 'thinkrank')}
                        checked={integrationsSettings.ga4_auto_inject}
                        onChange={(value) => handleIntegrationsSettingChange('ga4_auto_inject', value)}
                        help={__('Automatically add GA4 tracking code to your website. Disable if you\'ve already installed GA4 manually or via another plugin.', 'thinkrank')}
                        __nextHasNoMarginBottom={true}
                        className="thinkrank-mb-sm"
                    />

                    {/* Advanced Options */}
                    {integrationsSettings.ga4_auto_inject && (
                        <div className="thinkrank-p-4 thinkrank-bg-gray-50 thinkrank-border thinkrank-border-light thinkrank-rounded thinkrank-mt-md">
                            <h4 className="thinkrank-mt-0 thinkrank-mb-3 thinkrank-text-primary thinkrank-text-sm thinkrank-font-semibold">{__('Advanced Options', 'thinkrank')}</h4>



                            <ToggleControl
                                label={__('Anonymize IP addresses', 'thinkrank')}
                                checked={integrationsSettings.ga4_anonymize_ip}
                                onChange={(value) => handleIntegrationsSettingChange('ga4_anonymize_ip', value)}
                                help={__('Anonymize visitor IP addresses for GDPR compliance.', 'thinkrank')}
                                __nextHasNoMarginBottom={true}
                                className="thinkrank-mb-sm"
                            />

                            <ToggleControl
                                label={__('Exclude admin users', 'thinkrank')}
                                checked={integrationsSettings.ga4_exclude_admin}
                                onChange={(value) => handleIntegrationsSettingChange('ga4_exclude_admin', value)}
                                help={__('Exclude logged-in administrators from tracking.', 'thinkrank')}
                                __nextHasNoMarginBottom={true}
                                className="thinkrank-mb-sm"
                            />
                        </div>
                    )}

                    {/* Verification Section */}
                    <div className="thinkrank-pt-4 thinkrank-border-t thinkrank-border-light thinkrank-mt-md">
                        <Flex justify="space-between" align="center">
                            <FlexItem>
                                <Button
                                    variant="secondary"
                                    onClick={verifyTracking}
                                    isBusy={isVerifying}
                                    disabled={!integrationsSettings.ga4_measurement_id}
                                >
                                    {__('Verify Tracking', 'thinkrank')}
                                </Button>
                            </FlexItem>

                            {integrationsSettings.ga4_tracking_verified && integrationsSettings.ga4_last_verification && (
                                <FlexItem>
                                    <Text variant="muted" size="small">
                                        {__('Last verified:', 'thinkrank')} {integrationsSettings.ga4_last_verification}
                                    </Text>
                                </FlexItem>
                            )}
                        </Flex>

                        {verificationResult && (
                            <Notice
                                status={verificationResult.success ? 'success' : 'warning'}
                                isDismissible={false}
                                className="thinkrank-mt-sm"
                            >
                                {verificationResult.message}
                            </Notice>
                        )}
                    </div>
                </CardBody>
            </Card>
        </div>
    );

    /**
     * Render Social Platforms section
     * DRY: Moved from Social Media tab, preserving exact functionality
     */
    const renderSocialPlatforms = () => (
        <div className="thinkrank-tab-content">
            {/* Social Platform Verification Workflow */}
            <Card size="small" className="thinkrank-mb-md">
                <CardBody>
                    <div style={{
                        padding: '12px',
                        backgroundColor: '#e7f3ff',
                        border: '1px solid #b3d9ff',
                        borderRadius: '4px',
                        marginBottom: '16px'
                    }}>
                        <h4 style={{ margin: '0 0 8px 0', color: '#0073aa' }}>
                            {__('Social Platform Verification Workflow', 'thinkrank')}
                        </h4>
                        <ol style={{ margin: '0', paddingLeft: '20px', color: '#0073aa' }}>
                            <li>{__('Get verification codes from platform business accounts', 'thinkrank')}</li>
                            <li>{__('Configure platform IDs and verification codes below', 'thinkrank')}</li>
                            <li>{__('Verify website ownership with social platforms', 'thinkrank')}</li>
                            <li>{__('Access analytics and business features', 'thinkrank')}</li>
                        </ol>
                    </div>
                </CardBody>
            </Card>

            <div className="thinkrank-settings-grid">
                <Card size="small" className="thinkrank-mb-md">
                    <CardHeader>
                        <h3>{__('Facebook', 'thinkrank')}</h3>
                    </CardHeader>
                    <CardBody>
                        <TextControl
                            label={__('Facebook App ID', 'thinkrank')}
                            value={socialSettings.facebook_app_id}
                            onChange={(value) => handleSocialSettingChange('facebook_app_id', value)}
                            placeholder="123456789012XXXX"
                            help={
                                <>
                                    {__('Your Facebook App ID for analytics. ', 'thinkrank')}
                                    <a href="https://developers.facebook.com/apps/" target="_blank" rel="noopener noreferrer">
                                        {__('Get your App ID here →', 'thinkrank')}
                                    </a>
                                </>
                            }
                            __next40pxDefaultSize={true}
                            __nextHasNoMarginBottom={true}
                            className="thinkrank-mb-sm"
                        />

                        <TextControl
                            label={__('Facebook Admins', 'thinkrank')}
                            value={socialSettings.facebook_admins}
                            onChange={(value) => handleSocialSettingChange('facebook_admins', value)}
                            placeholder="100012345678XXXX,100087654321XXXX"
                            help={
                                <>
                                    {__('Comma-separated Facebook user IDs for admin access. ', 'thinkrank')}
                                    <a href="https://www.facebook.com/help/1503421039731588" target="_blank" rel="noopener noreferrer">
                                        {__('How to find your Facebook ID →', 'thinkrank')}
                                    </a>
                                </>
                            }
                            __next40pxDefaultSize={true}
                            __nextHasNoMarginBottom={true}
                        />
                    </CardBody>
                </Card>

                <Card size="small" className="thinkrank-mb-md">
                    <CardHeader>
                        <h3>{__('Pinterest', 'thinkrank')}</h3>
                    </CardHeader>
                    <CardBody>
                        <TextControl
                            label={__('Pinterest Site Verification', 'thinkrank')}
                            value={socialSettings.pinterest_site_verification}
                            onChange={(value) => handleSocialSettingChange('pinterest_site_verification', value)}
                            placeholder="a1b2c3d4e5f6789XXXX"
                            help={
                                <>
                                    {__('Pinterest site verification code for Pinterest Business. This will be encrypted and stored securely. ', 'thinkrank')}
                                    <a href="https://help.pinterest.com/en/business/article/claim-your-website" target="_blank" rel="noopener noreferrer">
                                        {__('Get verification code →', 'thinkrank')}
                                    </a>
                                </>
                            }
                            __next40pxDefaultSize={true}
                            __nextHasNoMarginBottom={true}
                        />
                    </CardBody>
                </Card>

                <Card size="small" className="thinkrank-mb-md">
                    <CardHeader>
                        <h3>{__('Instagram', 'thinkrank')}</h3>
                    </CardHeader>
                    <CardBody>
                        <TextControl
                            label={__('Instagram Verification', 'thinkrank')}
                            value={socialSettings.instagram_verification}
                            onChange={(value) => handleSocialSettingChange('instagram_verification', value)}
                            placeholder="ig_business_verify_123XXXX"
                            help={
                                <>
                                    {__('Instagram verification code for business features. This will be encrypted and stored securely. ', 'thinkrank')}
                                    <a href="https://business.instagram.com/getting-started" target="_blank" rel="noopener noreferrer">
                                        {__('Instagram Business setup →', 'thinkrank')}
                                    </a>
                                </>
                            }
                            __next40pxDefaultSize={true}
                            __nextHasNoMarginBottom={true}
                        />
                    </CardBody>
                </Card>

                <Card size="small" className="thinkrank-mb-md">
                    <CardHeader>
                        <h3>{__('TikTok', 'thinkrank')}</h3>
                    </CardHeader>
                    <CardBody>
                        <TextControl
                            label={__('TikTok Verification', 'thinkrank')}
                            value={socialSettings.tiktok_verification}
                            onChange={(value) => handleSocialSettingChange('tiktok_verification', value)}
                            placeholder="tiktok_biz_verify_456XXXX"
                            help={
                                <>
                                    {__('TikTok verification code for business features. This will be encrypted and stored securely. ', 'thinkrank')}
                                    <a href="https://support.tiktok.com/en/using-tiktok/growing-your-audience/switching-to-a-creator-or-business-account" target="_blank" rel="noopener noreferrer">
                                        {__('TikTok Business account setup →', 'thinkrank')}
                                    </a>
                                </>
                            }
                            __next40pxDefaultSize={true}
                            __nextHasNoMarginBottom={true}
                        />
                    </CardBody>
                </Card>

                <Card size="small" className="thinkrank-mb-md">
                    <CardHeader>
                        <h3>{__('YouTube', 'thinkrank')}</h3>
                    </CardHeader>
                    <CardBody>
                        <TextControl
                            label={__('YouTube Channel ID', 'thinkrank')}
                            value={socialSettings.youtube_channel_id}
                            onChange={(value) => handleSocialSettingChange('youtube_channel_id', value)}
                            placeholder="UCabcdefghijklmnXXXX"
                            help={
                                <>
                                    {__('Your YouTube channel ID (starts with UC). ', 'thinkrank')}
                                    <a href="https://support.google.com/youtube/answer/3250431" target="_blank" rel="noopener noreferrer">
                                        {__('Find your Channel ID →', 'thinkrank')}
                                    </a>
                                </>
                            }
                            __next40pxDefaultSize={true}
                            __nextHasNoMarginBottom={true}
                        />
                    </CardBody>
                </Card>

                <Card size="small" className="thinkrank-mb-md">
                    <CardHeader>
                        <h3>{__('WhatsApp Business', 'thinkrank')}</h3>
                    </CardHeader>
                    <CardBody>
                        <TextControl
                            label={__('WhatsApp Business ID', 'thinkrank')}
                            value={socialSettings.whatsapp_business_id}
                            onChange={(value) => handleSocialSettingChange('whatsapp_business_id', value)}
                            placeholder="1234567890XXXX"
                            help={
                                <>
                                    {__('Your WhatsApp Business account ID (digits only). ', 'thinkrank')}
                                    <a href="https://developers.facebook.com/docs/graph-api/reference/whats-app-business-account/" target="_blank" rel="noopener noreferrer">
                                        {__('WhatsApp Business API setup →', 'thinkrank')}
                                    </a>
                                </>
                            }
                            __next40pxDefaultSize={true}
                            __nextHasNoMarginBottom={true}
                        />
                    </CardBody>
                </Card>
            </div>
        </div>
    );

    if (isLoading) {
        return (
            <div style={{ textAlign: 'center', padding: '48px' }}>
                <Spinner />
                <Text>{__('Loading integration settings...', 'thinkrank')}</Text>
            </div>
        );
    }

    return (
        <div className="thinkrank-integrations-tab">
            {notice && (
                <Notice
                    status={notice.status}
                    onRemove={() => setNotice(null)}
                    className="thinkrank-mb-md"
                >
                    {notice.message}
                </Notice>
            )}

            {/* Render content based on active sub-section */}
            {(() => {
                switch (activeSubSection) {
                    case 'google-services':
                        return renderGoogleServices();
                    case 'social-platforms':
                        return renderSocialPlatforms();
                    default:
                        return renderGoogleServices();
                }
            })()}

            {/* Save Button */}
            <Flex justify="flex-end" className="thinkrank-mt-lg">
                <FlexItem>
                    <Button
                        variant="primary"
                        onClick={saveSettings}
                        isBusy={isSaving}
                        disabled={!hasChanges || isSaving}
                    >
                        {isSaving ? __('Saving...', 'thinkrank') : __('Save Changes', 'thinkrank')}
                    </Button>
                </FlexItem>
            </Flex>
        </div>
    );
};

export default IntegrationsTab;

```
