import { useState, useEffect } from '@wordpress/element'
import SettingToggle from './common/SettingToggle';
import { __, sprintf } from '@wordpress/i18n';

const LoginLogoutSettings = ({ settings }) => {
    const loginLogoutSettings = settings?.login_logout || {};

    const [isCustomUrlEnabled, setIsCustomUrlEnabled] = useState(
        loginLogoutSettings.enable_slug_change === '1'
    );

    const [customUrl, setCustomUrl] = useState(
        loginLogoutSettings.wpironis_custom_login_slug || 'wp-admin'
    );

    const [isSessionTimeoutEnabled, setIsSessionTimeoutEnabled] = useState(
        loginLogoutSettings.enable_session_timeout === '1'
    );

    const [sessionTimeout, setSessionTimeout] = useState(
        loginLogoutSettings.session_timeout_value || '3600'
    );

    const [isLimitLoginEnabled, setIsLimitLoginEnabled] = useState(
        loginLogoutSettings.enable_limit_login_attempts === '1'
    );

    const [loginAttempts, setLoginAttempts] = useState(
        loginLogoutSettings.wpironis_limit_login_attempts || '5'
    );

    const [lockoutDuration, setLockoutDuration] = useState(
        loginLogoutSettings.wpironis_lockout_duration || '3600'
    );

    const [isUserEnumEnabled, setIsUserEnumEnabled] = useState(
        loginLogoutSettings.enable_user_enumeration === '1'
    );

    const [userEnumMessage, setUserEnumMessage] = useState(
        loginLogoutSettings.user_enumeration_message || __('Wrong Login credentials', 'iron-security')
    );

    const [isLimitAdminsEnabled, setIsLimitAdminsEnabled] = useState(
        loginLogoutSettings.enable_limit_admins === '1'
    );

    const [maxAdmins, setMaxAdmins] = useState(
        loginLogoutSettings.wpironis_max_admins || '1'
    );

    const [fallbackRole, setFallbackRole] = useState(
        loginLogoutSettings.wpironis_admin_fallback_role || 'editor'
    );

    const [currentAdminCount, setCurrentAdminCount] = useState(
        loginLogoutSettings.current_admin_count || 0
    );

    const [adminUsers, setAdminUsers] = useState(
        loginLogoutSettings.admin_users || []
    );

    const [isAdminIdProtectionEnabled, setIsAdminIdProtectionEnabled] = useState(
        loginLogoutSettings.enable_admin_id_protection === '1'
    );
    const [currentAdminId, setCurrentAdminId] = useState(
        loginLogoutSettings.current_admin_id || '1'
    );

    const [isSaving, setIsSaving] = useState(false);
    const [notification, setNotification] = useState(null);

    const [isLoadingAdminInfo, setIsLoadingAdminInfo] = useState(false);

    const [isChangeAdminUsernameEnabled, setIsChangeAdminUsernameEnabled] = useState(
        loginLogoutSettings.enable_change_admin_username === '1'
    );

    const [newAdminUsername, setNewAdminUsername] = useState(
        loginLogoutSettings.wpironis_new_admin_username || ''
    );

    const [newAdminNickname, setNewAdminNickname] = useState(
        loginLogoutSettings.wpironis_new_admin_nickname || ''
    );

    const [adminUsernameStatus, setAdminUsernameStatus] = useState(null);


    const [is2FAEnabled, setIs2FAEnabled] = useState(
        loginLogoutSettings.enable_2fa === '1'
    );

    const [requiredRoles, setRequiredRoles] = useState(
        loginLogoutSettings.required_2fa_roles ? 
        JSON.parse(loginLogoutSettings.required_2fa_roles) : 
        ['administrator']
    );

    const [gracePeriod, setGracePeriod] = useState(
        loginLogoutSettings.grace_period || '1'
    );

    const [rememberDevice, setRememberDevice] = useState(
        loginLogoutSettings.remember_device || '7'
    );

    const getAdminCountStatus = () => {
        if (!isLimitAdminsEnabled || !maxAdmins) return 'normal';

        const maxAdminsNum = parseInt(maxAdmins);
        const currentCount = parseInt(currentAdminCount);

        if (currentCount > maxAdminsNum) return 'danger';
        if (currentCount === maxAdminsNum) return 'warning';
        if (currentCount >= Math.floor(maxAdminsNum * 0.75)) return 'caution';
        return 'normal';
    };

    const getAdminCountMessage = () => {
        const status = getAdminCountStatus();
        const maxAdminsNum = parseInt(maxAdmins);

        switch(status) {
            case 'danger':
                return sprintf(__('Warning: You have %1$s administrators which exceeds your limit of %2$s. Some administrators will be demoted to %3$s when you save.', 'iron-security'), 
                    currentAdminCount, maxAdmins, fallbackRole);
            case 'warning':
                return sprintf(__('You have reached your maximum number of administrators (%1$s). Adding more will result in automatic demotion to %2$s.', 'iron-security'), 
                    maxAdmins, fallbackRole);
            case 'caution':
                return sprintf(__('You are approaching your maximum number of administrators (%1$s of %2$s).', 'iron-security'), 
                    currentAdminCount, maxAdmins);
            default:
                return sprintf(__('Current administrator count: %1$s of %2$s maximum allowed.', 'iron-security'), 
                    currentAdminCount, maxAdmins);
        }
    };

    useEffect(() => {

        if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
            const globalSettings = window.ironSecurityDashboard.settings;
            const loginLogoutSettings = globalSettings?.login_logout || {};

            setIsCustomUrlEnabled(loginLogoutSettings.enable_slug_change === '1');
            setCustomUrl(loginLogoutSettings.wpironis_custom_login_slug || 'wp-admin');
            setIsSessionTimeoutEnabled(loginLogoutSettings.enable_session_timeout === '1');
            setSessionTimeout(loginLogoutSettings.session_timeout_value || '3600');
            setIsLimitLoginEnabled(loginLogoutSettings.enable_limit_login_attempts === '1');
            setLoginAttempts(loginLogoutSettings.wpironis_limit_login_attempts || '5');
            setLockoutDuration(loginLogoutSettings.wpironis_lockout_duration || '3600');
            setIsUserEnumEnabled(loginLogoutSettings.enable_user_enumeration === '1');
            setUserEnumMessage(loginLogoutSettings.user_enumeration_message || __('Wrong Login credentials', 'iron-security'));
            setIsLimitAdminsEnabled(loginLogoutSettings.enable_limit_admins === '1');
            setMaxAdmins(loginLogoutSettings.wpironis_max_admins || '1');
            setFallbackRole(loginLogoutSettings.wpironis_admin_fallback_role || 'editor');
            setCurrentAdminCount(loginLogoutSettings.current_admin_count || 0);

            if (loginLogoutSettings.admin_users) {
                setAdminUsers(loginLogoutSettings.admin_users);
            }

            if (loginLogoutSettings.current_admin_id) {
                setCurrentAdminId(loginLogoutSettings.current_admin_id);
            }

            setIsAdminIdProtectionEnabled(loginLogoutSettings.enable_admin_id_protection === '1');
            setIsChangeAdminUsernameEnabled(loginLogoutSettings.enable_change_admin_username === '1');

            if (loginLogoutSettings.wpironis_new_admin_username) {
                setNewAdminUsername(loginLogoutSettings.wpironis_new_admin_username);
            }

            if (loginLogoutSettings.wpironis_new_admin_nickname) {
                setNewAdminNickname(loginLogoutSettings.wpironis_new_admin_nickname);
            }

            setIs2FAEnabled(loginLogoutSettings.enable_2fa === '1');
            
            setRequiredRoles(
                loginLogoutSettings.required_2fa_roles ? 
                JSON.parse(loginLogoutSettings.required_2fa_roles) : 
                ['administrator']
            );
            
            setGracePeriod(loginLogoutSettings.grace_period || '1');
            setRememberDevice(loginLogoutSettings.remember_device || '7');
        } else {
            const loginLogoutSettings = settings?.login_logout || {};

            setIsCustomUrlEnabled(loginLogoutSettings.enable_slug_change === '1');
            setCustomUrl(loginLogoutSettings.wpironis_custom_login_slug || 'wp-admin');
            setIsSessionTimeoutEnabled(loginLogoutSettings.enable_session_timeout === '1');
            setSessionTimeout(loginLogoutSettings.session_timeout_value || '3600');
            setIsLimitLoginEnabled(loginLogoutSettings.enable_limit_login_attempts === '1');
            setLoginAttempts(loginLogoutSettings.wpironis_limit_login_attempts || '5');
            setLockoutDuration(loginLogoutSettings.wpironis_lockout_duration || '3600');
            setIsUserEnumEnabled(loginLogoutSettings.enable_user_enumeration === '1');
            setUserEnumMessage(loginLogoutSettings.user_enumeration_message || __('Wrong Login credentials', 'iron-security'));
            setIsLimitAdminsEnabled(loginLogoutSettings.enable_limit_admins === '1');
            setMaxAdmins(loginLogoutSettings.wpironis_max_admins || '1');
            setFallbackRole(loginLogoutSettings.wpironis_admin_fallback_role || 'editor');
            setCurrentAdminCount(loginLogoutSettings.current_admin_count || 0);

            if (loginLogoutSettings.admin_users) {
                setAdminUsers(loginLogoutSettings.admin_users);
            }

            if (loginLogoutSettings.current_admin_id) {
                setCurrentAdminId(loginLogoutSettings.current_admin_id);
            }

            if (loginLogoutSettings.enable_admin_id_protection === '1') {
                setIsAdminIdProtectionEnabled(true);
            }

            if (loginLogoutSettings.enable_change_admin_username === '1') {
                setIsChangeAdminUsernameEnabled(true);
            }

            if (loginLogoutSettings.wpironis_new_admin_username) {
                setNewAdminUsername(loginLogoutSettings.wpironis_new_admin_username);
            }

            if (loginLogoutSettings.wpironis_new_admin_nickname) {
                setNewAdminNickname(loginLogoutSettings.wpironis_new_admin_nickname);
            }
        }
    }, [settings]);

    useEffect(() => {
        if (isLimitAdminsEnabled) {
            fetchAdminInfo();
        }
    }, [isLimitAdminsEnabled]);

    useEffect(() => {
        if (isLimitAdminsEnabled && parseInt(currentAdminCount) > 0) {
            const status = getAdminCountStatus();

            if (status === 'danger' || status === 'warning') {
                showNotification(getAdminCountMessage(), status === 'danger' ? 'error' : 'warning');
            }
        }
    }, [maxAdmins]);

    useEffect(() => {
        if (notification) {
            document.body.classList.add('iron-security-notification-active');
        } else {
            document.body.classList.remove('iron-security-notification-active');
        }
        return () => {
            document.body.classList.remove('iron-security-notification-active');
        };
    }, [notification]);

    const showNotification = (message, type = 'success') => {
        setNotification({ message, type });
        setTimeout(() => setNotification(null), 3000);
    };

    const fetchAdminInfo = async () => {
        setIsLoadingAdminInfo(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_get_admin_info');
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setCurrentAdminCount(data.data.count);
                setAdminUsers(data.data.users);

                if (parseInt(data.data.count) > parseInt(maxAdmins) && parseInt(maxAdmins) > 0) {
                    showNotification(sprintf(__('Warning: You have %1$s administrators which exceeds your limit of %2$s. Some administrators will be demoted when you save these settings.', 'iron-security'), data.data.count, maxAdmins), 'warning');
                }
            } else {
                throw new Error(data.data || __('Failed to fetch admin information', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to fetch admin information', 'iron-security'), 'error');
        } finally {
            setIsLoadingAdminInfo(false);
        }
    };

    const handleCustomUrlToggle = async (enabled) => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_custom_url');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setIsCustomUrlEnabled(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        enable_slug_change: enabled ? '1' : '0'
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('Custom URL setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to update custom URL setting', 'iron-security'), 'error');
            setIsCustomUrlEnabled(!enabled);
        } finally {
            setIsSaving(false);
        }
    };

    const handleCustomUrlSave = async () => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_save_custom_url');
            formData.append('url', customUrl.toLowerCase().replace(/\s+/g, '-'));
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setCustomUrl(data.data.url);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        wpironis_custom_login_slug: data.data.url
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('Custom URL saved successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to save custom URL', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to save custom URL', 'iron-security'), 'error');
        } finally {
            setIsSaving(false);
        }
    };

    const handleSessionTimeoutToggle = async (enabled) => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_session_timeout');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setIsSessionTimeoutEnabled(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        enable_session_timeout: enabled ? '1' : '0'
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('Session timeout setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to update session timeout setting', 'iron-security'), 'error');
            setIsSessionTimeoutEnabled(!enabled);
        } finally {
            setIsSaving(false);
        }
    };

    const handleSessionTimeoutSave = async () => {
        setIsSaving(true);

        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_save_session_timeout');
            formData.append('timeout', sessionTimeout);
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setSessionTimeout(data.data.timeout);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        session_timeout_value: data.data.timeout
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('Session timeout value saved successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to save session timeout', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to save session timeout', 'iron-security'), 'error');
        } finally {
            setIsSaving(false);
        }
    };

    const handleLimitLoginToggle = async (enabled) => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_limit_login');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setIsLimitLoginEnabled(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        enable_limit_login_attempts: enabled ? '1' : '0'
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('Limit login attempts setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to update limit login setting', 'iron-security'), 'error');
            setIsLimitLoginEnabled(!enabled);
        } finally {
            setIsSaving(false);
        }
    };

    const handleLimitLoginSave = async () => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_save_limit_login');
            formData.append('attempts', loginAttempts);
            formData.append('duration', lockoutDuration);
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        wpironis_limit_login_attempts: loginAttempts,
                        wpironis_lockout_duration: lockoutDuration
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('Login attempt limits saved successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to save login attempt limits', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to save login attempt limits', 'iron-security'), 'error');
        } finally {
            setIsSaving(false);
        }
    };

    const handleLimitAdminsToggle = async (enabled) => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_limit_admins');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setIsLimitAdminsEnabled(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        enable_limit_admins: enabled ? '1' : '0'
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }

                if (enabled) {
                    await fetchAdminInfo();
                }

                showNotification(data.data.message || __('Admin limitation setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to update admin limitation setting', 'iron-security'), 'error');
            setIsLimitAdminsEnabled(!enabled);
        } finally {
            setIsSaving(false);
        }
    };

    const handleLimitAdminsSave = async () => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_save_limit_admins');
            formData.append('max_admins', maxAdmins);
            formData.append('fallback_role', fallbackRole);
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        wpironis_max_admins: maxAdmins,
                        wpironis_admin_fallback_role: fallbackRole
                    };
                }
                
                await fetchAdminInfo();
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    if (adminUsers) {
                        window.ironSecurityDashboard.settings.login_logout.admin_users = adminUsers;
                        window.ironSecurityDashboard.settings.login_logout.current_admin_count = adminUsers.length;
                    }
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }

                showNotification(data.data.message || __('Admin limitation settings saved successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to save admin limitation settings', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to save admin limitation settings', 'iron-security'), 'error');
        } finally {
            setIsSaving(false);
        }
    };

    const handleUserEnumToggle = async (enabled) => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_user_enum');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setIsUserEnumEnabled(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        enable_user_enumeration: enabled ? '1' : '0'
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('User enumeration protection setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to update user enumeration protection setting', 'iron-security'), 'error');
            setIsUserEnumEnabled(!enabled);
        } finally {
            setIsSaving(false);
        }
    };

    const handleUserEnumMessageSave = async () => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_save_user_enum_message');
            formData.append('message', userEnumMessage);
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        user_enumeration_message: userEnumMessage
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('Custom error message saved successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to save custom error message', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to save custom error message', 'iron-security'), 'error');
        } finally {
            setIsSaving(false);
        }
    };

    const handleAdminIdProtectionToggle = async (enabled) => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_admin_id_protection');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setIsAdminIdProtectionEnabled(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        enable_admin_id_protection: enabled ? '1' : '0'
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                if (data.data.admin_id) {
                    setCurrentAdminId(data.data.admin_id);
                    

                    if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                        window.ironSecurityDashboard.settings.login_logout.current_admin_id = data.data.admin_id;
                    }
                }

                let notificationType = 'success';
                if (enabled && data.data.admin_id !== '1') {
                    notificationType = 'success';
                }

                showNotification(data.data.message || __('Admin ID protection setting updated successfully', 'iron-security'), notificationType);
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to update admin ID protection setting', 'iron-security'), 'error');
            setIsAdminIdProtectionEnabled(!enabled);
        } finally {
            setIsSaving(false);
        }
    };

    const handleChangeAdminUsernameToggle = async (enabled) => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_change_admin_username');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setIsChangeAdminUsernameEnabled(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        enable_change_admin_username: enabled ? '1' : '0'
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }

                if (enabled && data.data.admin_usernames && data.data.admin_usernames.length > 0) {
                    setAdminUsernameStatus({
                        message: sprintf(__('Insecure admin usernames detected: %s. Change them to improve security.', 'iron-security'), data.data.admin_usernames.join(', ')),
                        type: 'warning'
                    });


                    if (!newAdminUsername) {
                        generateRandomUsername();
                    }
                } else if (enabled) {
                    setAdminUsernameStatus({
                        message: __('No insecure admin usernames detected.', 'iron-security'),
                        type: 'info'
                    });
                } else {
                    setAdminUsernameStatus(null);
                }

                showNotification(data.data.message || __('Change admin username setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to update change admin username setting', 'iron-security'), 'error');
            setIsChangeAdminUsernameEnabled(!enabled);
        } finally {
            setIsSaving(false);
        }
    };

    const handleSaveAdminUsername = async () => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_save_change_admin_username');
            formData.append('new_username', newAdminUsername);
            formData.append('new_nickname', newAdminNickname);
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        wpironis_new_admin_username: newAdminUsername,
                        wpironis_new_admin_nickname: newAdminNickname
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                if (data.data.changed_users && data.data.changed_users.length > 0) {
                    const changedUsers = data.data.changed_users;
                    let message = __('The following admin usernames were changed:', 'iron-security') + '\n';

                    changedUsers.forEach(user => {
                        message += `• ${user.old_username} → ${user.new_username}`;
                        if (user.display_name) {
                            message += ` (${user.display_name}`;
                            if (user.old_nickname && user.new_nickname) {
                                message += `, nickname: ${user.old_nickname} → ${user.new_nickname}`;
                            }
                            message += `)`;
                        }
                        message += '\n';
                    });

                    setAdminUsernameStatus({
                        message: __('Admin usernames successfully changed.', 'iron-security'),
                        type: 'info'
                    });

                    showNotification(data.data.message || __('Admin usernames changed successfully', 'iron-security'));
                    setTimeout(() => {
                        alert(message);
                    }, 500);
                } else {
                    setAdminUsernameStatus({
                        message: __('New admin username saved. No insecure admin usernames found to change.', 'iron-security'),
                        type: 'info'
                    });
                    showNotification(data.data.message || __('New admin username saved successfully', 'iron-security'));
                }
            } else {
                throw new Error(data.data || __('Failed to save new admin username', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to save new admin username', 'iron-security'), 'error');
        } finally {
            setIsSaving(false);
        }
    };

    const generateRandomUsername = () => {
        const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        let result = '';
        const length = 8 + Math.floor(Math.random() * 8);
        for (let i = 0; i < length; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        setNewAdminUsername(result);
        setNewAdminNickname(result);
    };
    

    const handle2FAToggle = async (enabled) => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_toggle_2fa');
            formData.append('enabled', enabled);
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {
                setIs2FAEnabled(enabled);
                

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        enable_2fa: enabled ? '1' : '0'
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('Two-factor authentication setting updated successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to update setting', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to update two-factor authentication setting', 'iron-security'), 'error');
            setIs2FAEnabled(!enabled);
        } finally {
            setIsSaving(false);
        }
    };


    const handle2FASettingsSave = async () => {
        setIsSaving(true);
        try {
            const formData = new FormData();
            formData.append('action', 'iron_security_save_2fa_settings_loginlogout');
            formData.append('required_roles', JSON.stringify(requiredRoles));
            formData.append('grace_period', gracePeriod);
            formData.append('remember_device', rememberDevice);
            formData.append('nonce', settings.nonce);

            const response = await fetch(ajaxurl, {
                method: 'POST',
                body: formData,
                credentials: 'same-origin'
            });

            const data = await response.json();

            if (data.success) {

                if (window.ironSecurityDashboard && window.ironSecurityDashboard.settings) {
                    window.ironSecurityDashboard.settings.login_logout = {
                        ...window.ironSecurityDashboard.settings.login_logout,
                        required_2fa_roles: JSON.stringify(requiredRoles),
                        grace_period: gracePeriod,
                        remember_device: rememberDevice
                    };
                    

                    if (window.ironSecurityDashboard.notifySettingsChange) {
                        window.ironSecurityDashboard.notifySettingsChange();
                    }
                }
                
                showNotification(data.data.message || __('Two-factor authentication settings saved successfully', 'iron-security'));
            } else {
                throw new Error(data.data || __('Failed to save two-factor authentication settings', 'iron-security'));
            }
        } catch (error) {
            console.error('Error:', error);
            showNotification(error.message || __('Failed to save two-factor authentication settings', 'iron-security'), 'error');
        } finally {
            setIsSaving(false);
        }
    };


    const handleRoleCheckboxChange = (role) => {
        if (requiredRoles.includes(role)) {
            setRequiredRoles(requiredRoles.filter(r => r !== role));
        } else {
            setRequiredRoles([...requiredRoles, role]);
        }
    };

    const formatDuration = (seconds) => {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);

        let formatted = '';
        if (hours > 0) {
            formatted += sprintf(__('%d hour%s ', 'iron-security'), hours, hours > 1 ? 's' : '');
        }
        if (minutes > 0) {
            formatted += sprintf(__('%d minute%s', 'iron-security'), minutes, minutes > 1 ? 's' : '');
        }
        if (!hours && !minutes) {
            formatted = sprintf(__('%d seconds', 'iron-security'), seconds);
        }
        return formatted.trim();
    };

    return (
        <>
            {notification && (
                <div className={`iron-security-notification ${notification.type}`}>
                    <span className={`dashicons dashicons-${notification.type === 'success' ? 'yes' : 'warning'}`} />
                    <span className="message">{notification.message}</span>
                    <button
                        className="close-button"
                        onClick={() => setNotification(null)}
                        aria-label={__("Close notification", "iron-security")}
                    >
                        <span className="dashicons dashicons-no" />
                    </button>
                </div>
            )}
            <div className="wpironis-settings-section">
                <div className="wpironis-setting-group">
                    <SettingToggle
                        label={__("Two-Factor Authentication (2FA)", "iron-security")}
                        description={__("Enable to require two-factor authentication for selected user roles to enhance login security.", "iron-security")}
                        checked={is2FAEnabled}
                        onChange={handle2FAToggle}
                        disabled={isSaving}
                    />

                    {is2FAEnabled && (
                        <div className="wpironis-custom-url-input">
                            <div className="wpironis-2fa-settings">
                                <h4>{__("Two-Factor Authentication Settings", "iron-security")}</h4>
                                
                                <div className="wpironis-input-group">
                                    <label>{__("Required Roles:", "iron-security")}</label>
                                    <div className="wpironis-roles-checkboxes">
                                        <label>
                                            <input 
                                                type="checkbox" 
                                                checked={requiredRoles.includes('administrator')} 
                                                onChange={() => handleRoleCheckboxChange('administrator')}
                                                disabled={isSaving}
                                            />
                                            {__("Administrator", "iron-security")}
                                        </label>
                                        <label>
                                            <input 
                                                type="checkbox" 
                                                checked={requiredRoles.includes('editor')} 
                                                onChange={() => handleRoleCheckboxChange('editor')}
                                                disabled={isSaving}
                                            />
                                            {__("Editor", "iron-security")}
                                        </label>
                                        <label>
                                            <input 
                                                type="checkbox" 
                                                checked={requiredRoles.includes('author')} 
                                                onChange={() => handleRoleCheckboxChange('author')}
                                                disabled={isSaving}
                                            />
                                            {__("Author", "iron-security")}
                                        </label>
                                        <label>
                                            <input 
                                                type="checkbox" 
                                                checked={requiredRoles.includes('contributor')} 
                                                onChange={() => handleRoleCheckboxChange('contributor')}
                                                disabled={isSaving}
                                            />
                                            {__("Contributor", "iron-security")}
                                        </label>
                                    </div>
                                    <p className="description">
                                        {__("Users with selected roles will be required to set up and use two-factor authentication.", "iron-security")}
                                    </p>
                                </div>

                                <div className="wpironis-input-group" style={{ marginTop: '15px' }}>
                                    <label htmlFor="grace-period">{__("Grace Period (days):", "iron-security")}</label>
                                    <input
                                        type="number"
                                        id="grace-period"
                                        value={gracePeriod}
                                        onChange={(e) => setGracePeriod(e.target.value)}
                                        min="0"
                                        max="30"
                                        disabled={isSaving}
                                    />
                                    <p className="description">
                                        {__("Number of days users have to set up 2FA after it becomes required. Set to 0 to require immediate setup.", "iron-security")}
                                    </p>
                                </div>

                                <div className="wpironis-input-group" style={{ marginTop: '15px' }}>
                                    <label htmlFor="remember-device">{__("Remember Device (days):", "iron-security")}</label>
                                    <input
                                        type="number"
                                        id="remember-device"
                                        value={rememberDevice}
                                        onChange={(e) => setRememberDevice(e.target.value)}
                                        min="0"
                                        max="90"
                                        disabled={isSaving}
                                    />
                                    <p className="description">
                                        {__("Number of days to remember a device after successful verification. Set to 0 to disable this option.", "iron-security")}
                                    </p>
                                </div>

                                <button
                                    className="button button-primary"
                                    onClick={handle2FASettingsSave}
                                    disabled={isSaving}
                                    style={{ marginTop: '15px' }}
                                >
                                    {isSaving ? __('Saving...', 'iron-security') : __('Save 2FA Settings', 'iron-security')}
                                </button>
                            </div>
                        </div>
                    )}
                    
                    <SettingToggle
                        label={__("Custom Admin Area URL", "iron-security")}
                        description={__("Enable to customize your WordPress admin area URL for enhanced security.", "iron-security")}
                        checked={isCustomUrlEnabled}
                        onChange={handleCustomUrlToggle}
                        disabled={isSaving}
                    />

                    {isCustomUrlEnabled && (
                        <div className="wpironis-custom-url-input">
                            <div className="wpironis-input-group">
                                <label htmlFor="custom-url">{__("Custom Admin URL:", "iron-security")}</label>
                                <input
                                    type="text"
                                    id="custom-url"
                                    value={customUrl}
                                    onChange={(e) => setCustomUrl(e.target.value.replace(/\s+/g, '-').toLowerCase())}
                                    placeholder={__("Enter custom URL (e.g., wp-admin)", "iron-security")}
                                    disabled={isSaving}
                                />
                                <button
                                    className="button button-primary"
                                    onClick={handleCustomUrlSave}
                                    disabled={isSaving}
                                >
                                    {isSaving ? __('Saving...', 'iron-security') : __('Save URL', 'iron-security')}
                                </button>
                            </div>
                            <p className="description">
                                {sprintf(__('Your admin area will be accessible at: %s/%s', 'iron-security'), 
                                    window.location.origin, customUrl.toLowerCase().replace(/\s+/g, '-'))}
                            </p>
                        </div>
                    )}

                    <SettingToggle
                        label={__("Limit Login Attempts", "iron-security")}
                        description={__("Enable to limit the number of failed login attempts before temporarily blocking the user.", "iron-security")}
                        checked={isLimitLoginEnabled}
                        onChange={handleLimitLoginToggle}
                        disabled={isSaving}
                    />

                    {isLimitLoginEnabled && (
                        <div className="wpironis-custom-url-input">
                            <div className="wpironis-input-group">
                                <label htmlFor="login-attempts">{__("Maximum Login Attempts:", "iron-security")}</label>
                                <input
                                    type="number"
                                    id="login-attempts"
                                    value={loginAttempts}
                                    onChange={(e) => setLoginAttempts(e.target.value)}
                                    placeholder={__("Enter number of attempts (e.g., 5)", "iron-security")}
                                    min="1"
                                    disabled={isSaving}
                                />
                            </div>
                            <div className="wpironis-input-group" style={{ marginTop: '10px' }}>
                                <label htmlFor="lockout-duration">{__("Lockout Duration (seconds):", "iron-security")}</label>
                                <input
                                    type="number"
                                    id="lockout-duration"
                                    value={lockoutDuration}
                                    onChange={(e) => setLockoutDuration(e.target.value)}
                                    placeholder="Enter lockout duration in seconds (e.g., 3600)"
                                    min="1"
                                    disabled={isSaving}
                                />
                                <button
                                    className="button button-primary"
                                    onClick={handleLimitLoginSave}
                                    disabled={isSaving}
                                    style={{ marginLeft: '10px' }}
                                >
                                    {isSaving ? __('Saving...', 'iron-security') : __('Save Settings', 'iron-security')}
                                </button>
                            </div>
                            <p className="description">
                                {sprintf(__('Users will be locked out for %1$s after %2$s failed login attempts.', 'iron-security'), 
                                    formatDuration(parseInt(lockoutDuration)),
                                    loginAttempts
                                )}
                            </p>
                        </div>
                    )}

                    <SettingToggle
                        label={__("Limit Administrators in WordPress", "iron-security")}
                        description={__("Restrict the number of administrator accounts to prevent unauthorized admin access.", "iron-security")}
                        checked={isLimitAdminsEnabled}
                        onChange={handleLimitAdminsToggle}
                        disabled={isSaving}
                    />

                    {isLimitAdminsEnabled && (
                        <div className="wpironis-custom-url-input">
                            {isLoadingAdminInfo ? (
                                <p className="description">{__("Loading administrator information...", "iron-security")}</p>
                            ) : (
                                <div className="admin-info-section">
                                    <p className={`description admin-count ${getAdminCountStatus()}`}>
                                        <strong>{getAdminCountMessage()}</strong>
                                    </p>
                                    {adminUsers && adminUsers.length > 0 && (
                                        <div className="admin-users-list">
                                            <p className="description">{__("Current administrators:", "iron-security")}</p>
                                            <ul>
                                                {adminUsers.map((admin, index) => (
                                                    <li key={index}>{admin.user_login} {admin.display_name ? `(${admin.display_name})` : ''} - {admin.user_email}</li>
                                                ))}
                                            </ul>
                                        </div>
                                    )}
                                </div>
                            )}
                            <div className="wpironis-input-group">
                                <label htmlFor="max-admins">{__("Maximum Number of Administrators:", "iron-security")}</label>
                                <input
                                    type="number"
                                    id="max-admins"
                                    value={maxAdmins}
                                    onChange={(e) => setMaxAdmins(e.target.value)}
                                    placeholder={__("Enter maximum number of admins (e.g., 1)", "iron-security")}
                                    min="1"
                                    disabled={isSaving}
                                />
                            </div>
                            <div className="wpironis-input-group" style={{ marginTop: '10px' }}>
                                <label htmlFor="fallback-role">{__("Fallback Role:", "iron-security")}</label>
                                <select
                                    id="fallback-role"
                                    value={fallbackRole}
                                    onChange={(e) => setFallbackRole(e.target.value)}
                                    disabled={isSaving}
                                >
                                    <option value="editor">{__("Editor", "iron-security")}</option>
                                    <option value="author">{__("Author", "iron-security")}</option>
                                    <option value="contributor">{__("Contributor", "iron-security")}</option>
                                    <option value="subscriber">{__("Subscriber", "iron-security")}</option>
                                </select>
                                <button
                                    className="button button-primary"
                                    onClick={handleLimitAdminsSave}
                                    disabled={isSaving}
                                    style={{ marginLeft: '10px' }}
                                >
                                    {isSaving ? __('Saving...', 'iron-security') : __('Save Settings', 'iron-security')}
                                </button>
                            </div>
                        </div>
                    )}

                    <SettingToggle
                        label={__("Session Timeout", "iron-security")}
                        description={__("Enable to set a custom session timeout duration for logged-in users.", "iron-security")}
                        checked={isSessionTimeoutEnabled}
                        onChange={handleSessionTimeoutToggle}
                        disabled={isSaving}
                    />

                    {isSessionTimeoutEnabled && (
                        <div className="wpironis-custom-url-input">
                            <div className="wpironis-input-group">
                                <label htmlFor="session-timeout">{__("Timeout (seconds):", "iron-security")}</label>
                                <input
                                    type="number"
                                    id="session-timeout"
                                    value={sessionTimeout}
                                    onChange={(e) => setSessionTimeout(e.target.value)}
                                    placeholder={__("Enter timeout in seconds (e.g., 3600 for 1 hour)", "iron-security")}
                                    min="1"
                                    disabled={isSaving}
                                />
                                <button
                                    className="button button-primary"
                                    onClick={handleSessionTimeoutSave}
                                    disabled={isSaving}
                                >
                                    {isSaving ? __('Saving...', 'iron-security') : __('Save Timeout', 'iron-security')}
                                </button>
                            </div>
                            <p className="description">
                                {sprintf(__('Users will be logged out after %1$s hours and %2$s minutes of inactivity', 'iron-security'),
                                    Math.floor(parseInt(sessionTimeout) / 3600),
                                    Math.floor((parseInt(sessionTimeout) % 3600) / 60)
                                )}
                            </p>
                        </div>
                    )}

                    <SettingToggle
                        label={__("Block User Enumeration", "iron-security")}
                        description={__("Prevent attackers from discovering usernames through author archives and REST API. This makes it harder for attackers to gather information about your users for targeted attacks.", "iron-security")}
                        checked={isUserEnumEnabled}
                        onChange={handleUserEnumToggle}
                        disabled={isSaving}
                    />

                    {isUserEnumEnabled && (
                        <div className="wpironis-custom-url-input">
                            <div className="wpironis-input-group">
                                <label htmlFor="user-enum-message">{__("Custom Error Message:", "iron-security")}</label>
                                <input
                                    type="text"
                                    id="user-enum-message"
                                    value={userEnumMessage}
                                    onChange={(e) => setUserEnumMessage(e.target.value)}
                                    placeholder={__("Enter custom error message", "iron-security")}
                                    disabled={isSaving}
                                />
                                <button
                                    className="button button-primary"
                                    onClick={handleUserEnumMessageSave}
                                    disabled={isSaving}
                                >
                                    {isSaving ? __('Saving...', 'iron-security') : __('Save Message', 'iron-security')}
                                </button>
                            </div>
                            <p className="description">
                                {sprintf(__('This message will be shown instead of the default WordPress login error message that reveals username information. For example, instead of "The password you entered for the username admin is incorrect", it will show "%s".', 'iron-security'), userEnumMessage)}
                            </p>
                        </div>
                    )}

                    <SettingToggle
                        label={__("Admin ID Protection", "iron-security")}
                        description={__("Change the default administrator ID (1) to a different value to protect against targeted attacks.", "iron-security")}
                        checked={isAdminIdProtectionEnabled}
                        onChange={handleAdminIdProtectionToggle}
                        disabled={isSaving}
                    />

                    {isAdminIdProtectionEnabled && (
                        <div className="wpironis-custom-url-input">
                            <div className="admin-id-info">
                                <p className="description">
                                    <strong>{__("Current Admin ID:", "iron-security")}</strong> {currentAdminId}
                                </p>
                                <p className="description">
                                    {currentAdminId === '1' ?
                                        __("The default WordPress administrator ID is typically 1, which is commonly targeted by attackers. When you enable this feature, the admin ID will be changed to a different value for enhanced security.", "iron-security") :
                                        __("Your administrator ID has been changed from the default value (1) to a different ID for enhanced security. This makes it harder for attackers to target your administrator account.", "iron-security")
                                    }
                                </p>
                                {currentAdminId === '1' ? (
                                    <p className="description admin-id-warning">
                                        <span className="dashicons dashicons-warning"></span> {__("Note: Changing the admin ID is a one-way operation. It will be changed automatically when this feature is enabled.", "iron-security")}
                                    </p>
                                ) : (
                                    <p className="description">
                                        <span className="dashicons dashicons-yes-alt"></span> {__("Your administrator ID has been successfully changed for improved security.", "iron-security")}
                                    </p>
                                )}
                            </div>
                        </div>
                    )}

                    <SettingToggle
                        label={__("Change Default Admin Username", "iron-security")}
                        description={__("Change admin username if you have accounts with usernames like 'admin' or 'administrator' to prevent targeted attacks.", "iron-security")}
                        checked={isChangeAdminUsernameEnabled}
                        onChange={handleChangeAdminUsernameToggle}
                        disabled={isSaving}
                    />

                    {isChangeAdminUsernameEnabled && (
                        <div className="wpironis-custom-url-input">
                            <div className="admin-username-info">
                                <p className="description">
                                    <strong>{__("Default admin usernames like 'admin' or 'administrator' are frequently targeted in brute force attacks.", "iron-security")}</strong>
                                    {__("Change them to enhance your site's security.", "iron-security")}
                                </p>
                                {adminUsernameStatus && (
                                    <p className={`description ${adminUsernameStatus.type}`}>
                                        <span className={`dashicons dashicons-${adminUsernameStatus.type === 'warning' ? 'warning' : 'info'}`}></span>
                                        {adminUsernameStatus.message}
                                    </p>
                                )}
                                <div className="wpironis-input-group">
                                    <label htmlFor="new-admin-username">{__("New Username:", "iron-security")}</label>
                                    <input
                                        type="text"
                                        id="new-admin-username"
                                        value={newAdminUsername}
                                        onChange={(e) => setNewAdminUsername(e.target.value.replace(/[^a-zA-Z]/g, ''))}
                                        placeholder={__("Enter new username (letters only)", "iron-security")}
                                        disabled={isSaving}
                                    />
                                    <button
                                        className="button button-secondary"
                                        onClick={generateRandomUsername}
                                        disabled={isSaving}
                                        style={{ marginLeft: '5px' }}
                                    >
                                        {__("Generate Random", "iron-security")}
                                    </button>
                                </div>
                                <div className="wpironis-input-group" style={{ marginTop: '10px' }}>
                                    <label htmlFor="new-admin-nickname">{__("New Nickname:", "iron-security")}</label>
                                    <input
                                        type="text"
                                        id="new-admin-nickname"
                                        value={newAdminNickname}
                                        onChange={(e) => setNewAdminNickname(e.target.value)}
                                        placeholder={__("Enter new nickname", "iron-security")}
                                        disabled={isSaving}
                                    />
                                    <p className="description" style={{ marginTop: '5px' }}>
                                        {__("The nickname is displayed publicly if chosen in the user's profile. Changing it prevents revealing the admin role.", "iron-security")}
                                    </p>
                                </div>
                                <div className="wpironis-input-group" style={{ marginTop: '10px' }}>
                                    <button
                                        className="button button-primary"
                                        onClick={handleSaveAdminUsername}
                                        disabled={isSaving || !newAdminUsername}
                                        style={{ marginLeft: '5px' }}
                                    >
                                        {isSaving ? __('Saving...', 'iron-security') : __('Save Username & Nickname', 'iron-security')}
                                    </button>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </>
    );
};

export default LoginLogoutSettings;