// User Name Edit Component
// Displays and configures user name with various display options

import { __ } from '@wordpress/i18n';
import {
    InspectorControls,
    useBlockProps
} from '@wordpress/block-editor';
import {
    PanelBody,
    SelectControl,
    ToggleControl,
    TextControl
} from '@wordpress/components';
import { Fragment } from '@wordpress/element';

const Edit = ({ attributes, setAttributes, context }) => {
    const {
        nameFormat,
        headingLevel,
        showRole,
        roleSeparator
    } = attributes;

    // Get user data from context prop (Query Loop style)
    	const user = context?.['wpuf-ud/userObject'] || {
        id: 0,
        display_name: __('Sample User', 'wpuf-pro'),
        user_login: 'sampleuser',
        user_email: 'sample@example.com',
        first_name: 'Sample',
        last_name: 'User',
        nickname: 'sample',
        roles: ['subscriber']
    };

    // Detect container context for styling
    	const containerLayout = context?.['wpuf-ud/containerLayout'] || 'default';
	const isInDirectory = context?.['wpuf-ud/isDirectoryMode'] || false;

    const blockProps = useBlockProps({
        className: `wpuf-user-name wpuf-container-${containerLayout} ${isInDirectory ? 'wpuf-in-directory' : 'wpuf-in-profile'}`
    });

    // Get display name based on format
    const getDisplayName = () => {
        // Handle both user_login and username fields (REST API returns 'username')
        const userLogin = user.user_login || user.username;
        
        switch (nameFormat) {
            case 'display_name':
                return user.display_name || userLogin;
            case 'first_last':
                const firstName = user.first_name || '';
                const lastName = user.last_name || '';
                const firstLast = `${firstName} ${lastName}`.trim();
                return firstLast || user.display_name || userLogin;
            case 'last_first':
                const last = user.last_name || '';
                const first = user.first_name || '';
                if (last && first) {
                    return `${last}, ${first}`;
                } else {
                    return user.display_name || userLogin;
                }
            case 'username':
                return userLogin || 'sampleuser';
            case 'nickname':
                return user.nickname || user.display_name || userLogin;
            default:
                return user.display_name || userLogin;
        }
    };

    const displayName = getDisplayName();
    const userRoles = user.roles || [];

    return (
        <Fragment>
            <InspectorControls>
                <PanelBody title={__('Name Settings', 'wpuf-pro')} initialOpen={true}>
                    <SelectControl
                        label={__('Name Format', 'wpuf-pro')}
                        value={nameFormat}
                        options={[
                            { label: __('Display Name', 'wpuf-pro'), value: 'display_name' },
                            { label: __('First Last', 'wpuf-pro'), value: 'first_last' },
                            { label: __('Last First', 'wpuf-pro'), value: 'last_first' },
                            { label: __('Username', 'wpuf-pro'), value: 'username' },
                            { label: __('Nickname', 'wpuf-pro'), value: 'nickname' }
                        ]}
                        onChange={(value) => setAttributes({ nameFormat: value })}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                    />

                    <SelectControl
                        label={__('Element Type', 'wpuf-pro')}
                        value={headingLevel}
                        options={[
                            { label: __('Paragraph', 'wpuf-pro'), value: 'p' },
                            { label: __('Span', 'wpuf-pro'), value: 'span' }
                        ]}
                        onChange={(value) => setAttributes({ headingLevel: value })}
                        __next40pxDefaultSize={true}
                        __nextHasNoMarginBottom={true}
                    />

                    <ToggleControl
                        label={__('Show User Role', 'wpuf-pro')}
                        checked={showRole}
                        onChange={(value) => setAttributes({ showRole: value })}
                        __nextHasNoMarginBottom={true}
                    />

                    {showRole && (
                        <TextControl
                            label={__('Role Separator', 'wpuf-pro')}
                            value={roleSeparator}
                            onChange={(value) => setAttributes({ roleSeparator: value })}
                            placeholder=", "
                            __next40pxDefaultSize={true}
                            __nextHasNoMarginBottom={true}
                        />
                    )}
                </PanelBody>
            </InspectorControls>

            <div {...blockProps}>
                {(() => {
                    const TagName = headingLevel;
                    const content = showRole && userRoles.length > 0
                        ? `${displayName}${roleSeparator}${userRoles.join(', ')}`
                        : displayName;

                    return (
                        <TagName className="wpuf-name-text">
                            {content}
                        </TagName>
                    );
                })()}
            </div>
        </Fragment>
    );
};

export default Edit;
