// ProfileView Component
// Enhanced with username, share code, and bio features

function ProfileView({ user, token, t, onUserUpdate }) {
    const [profile, setProfile] = useState(null);
    const [loading, setLoading] = useState(true);
    const [editing, setEditing] = useState({ username: false, bio: false });
    const [formData, setFormData] = useState({ username: '', bio: '' });
    const [error, setError] = useState('');
    const [success, setSuccess] = useState('');
    const [friends, setFriends] = useState([]);
    const [friendsLoading, setFriendsLoading] = useState(false);

    useEffect(() => {
        loadProfile();
        loadFriends();
    }, []);

    const loadProfile = async () => {
        try {
            const response = await fetch(API_URL + '/profile/me', {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            setProfile(data);
            setFormData({
                username: data.username || '',
                bio: data.bio || ''
            });
        } catch (err) {
            console.error('Failed to load profile:', err);
        } finally {
            setLoading(false);
        }
    };

    const updateUsername = async () => {
        setError('');
        setSuccess('');

        try {
            const response = await fetch(API_URL + '/profile/username', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ username: formData.username })
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.detail || 'Failed to update username');
            }

            const data = await response.json();
            setSuccess('Username updated successfully!');
            setEditing({ ...editing, username: false });
            loadProfile();
        } catch (err) {
            setError(err.message);
        }
    };

    const updateBio = async () => {
        setError('');
        setSuccess('');

        try {
            const response = await fetch(API_URL + '/profile/bio', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ bio: formData.bio })
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.detail || 'Failed to update bio');
            }

            setSuccess('Bio updated successfully!');
            setEditing({ ...editing, bio: false });
            loadProfile();
        } catch (err) {
            setError(err.message);
        }
    };

    const regenerateShareCode = async () => {
        if (!confirm('Are you sure you want to generate a new share code? Your old code will stop working.')) {
            return;
        }

        try {
            const response = await fetch(API_URL + '/profile/regenerate-code', {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${token}` }
            });

            const data = await response.json();
            alert('New share code generated!');
            loadProfile();
        } catch (err) {
            alert('Failed to regenerate code');
        }
    };

    const copyToClipboard = (text, label) => {
        navigator.clipboard.writeText(text);
        setSuccess(`${label} copied to clipboard!`);
        setTimeout(() => setSuccess(''), 3000);
    };

    const loadFriends = async () => {
        setFriendsLoading(true);
        try {
            const response = await fetch(API_URL + '/connections/my-friends', {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const data = await response.json();
            setFriends(data.friends || []);
        } catch (err) {
            console.error('Failed to load friends:', err);
        } finally {
            setFriendsLoading(false);
        }
    };

    if (loading) {
        return <div className="loading" style={{ padding: '2rem', textAlign: 'center' }}>Loading profile...</div>;

    }

    if (!profile) {
        return <div className="card" style={{ padding: '2rem', textAlign: 'center' }}>Failed to load profile</div>;
    }

    const profileLink = profile.username
        ? `${window.location.origin}/@${profile.username}`
        : `${window.location.origin}/user/${profile.id}`;

    return (
        <div className="fade-in" style={{ padding: '2rem', maxWidth: '800px', margin: '0 auto' }}>
            <h2 className="page-title" style={{ marginBottom: '2rem' }}>Profile</h2>

            {/* Success/Error Messages */}
            {success && (
                <div style={{
                    padding: '1rem',
                    background: 'var(--success-bg, #d4edda)',
                    color: 'var(--success-text, #155724)',
                    borderRadius: '8px',
                    marginBottom: '1rem'
                }}>
                    ✓ {success}
                </div>
            )}
            {error && (
                <div style={{
                    padding: '1rem',
                    background: 'var(--error-bg, #f8d7da)',
                    color: 'var(--error-text, #721c24)',
                    borderRadius: '8px',
                    marginBottom: '1rem'
                }}>
                    ✗ {error}
                </div>
            )}

            {/* Basic Info Card */}
            <div className="card" style={{ padding: '2rem', marginBottom: '1.5rem' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: '1.5rem', marginBottom: '1.5rem' }}>
                    <ProfilePhotoUpload
                        currentPhotoUrl={profile.photo_url}
                        userName={profile.name}
                        onPhotoUpdate={(newPhotoUrl) => {
                            const updatedProfile = { ...profile, photo_url: newPhotoUrl };
                            setProfile(updatedProfile);
                            // Propagate to Dashboard to update header
                            if (onUserUpdate) {
                                onUserUpdate({ photo_url: newPhotoUrl, profile_photo: newPhotoUrl });
                            }
                        }}
                        token={token}
                    />
                    <div style={{ flex: 1 }}>
                        <h3 style={{
                            fontSize: '24px',
                            fontWeight: '700',
                            marginBottom: '0.25rem',
                            wordBreak: 'break-word',
                            overflowWrap: 'break-word',
                            maxWidth: '100%'
                        }}>
                            {profile.name}
                        </h3>
                        <p style={{
                            fontSize: '14px',
                            color: 'var(--text-secondary)',
                            marginBottom: '0.5rem',
                            wordBreak: 'break-word',
                            overflowWrap: 'break-word',
                            maxWidth: '100%'
                        }}>
                            📧 {profile.email}
                        </p>
                        <span style={{
                            fontSize: '12px',
                            padding: '0.25rem 0.75rem',
                            background: 'var(--primary-light)',
                            borderRadius: '12px'
                        }}>
                            Member since {new Date(profile.created_at).toLocaleDateString()}
                        </span>
                    </div>
                </div>
            </div>

            {/* Discovery Info Card */}
            <div className="card" style={{ padding: '2rem', marginBottom: '1.5rem' }}>
                <h3 style={{ fontSize: '18px', fontWeight: '600', marginBottom: '1.5rem' }}>
                    🔍 Discovery Info
                </h3>

                {/* Username Section */}
                <div style={{ marginBottom: '1.5rem', padding: '1rem', background: 'var(--secondary-bg)', borderRadius: '8px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '0.5rem' }}>
                        <label style={{ fontSize: '13px', fontWeight: '600', color: 'var(--text-secondary)' }}>
                            USERNAME
                        </label>
                        {!editing.username && (
                            <button
                                onClick={() => setEditing({ ...editing, username: true })}
                                style={{
                                    padding: '0.25rem 0.75rem',
                                    fontSize: '12px',
                                    background: 'none',
                                    border: '1px solid var(--border-color)',
                                    borderRadius: '6px',
                                    cursor: 'pointer'
                                }}
                            >
                                ✏️ Edit
                            </button>
                        )}
                    </div>

                    {editing.username ? (
                        <div>
                            <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', marginBottom: '0.5rem' }}>
                                <span style={{ fontSize: '18px', color: 'var(--text-secondary)' }}>@</span>
                                <input
                                    value={formData.username}
                                    onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                                    placeholder="yourusername"
                                    className="form-input"
                                    style={{ flex: 1, padding: '0.5rem', fontSize: '16px' }}
                                />
                            </div>
                            <p style={{ fontSize: '12px', color: 'var(--text-tertiary)', marginBottom: '0.75rem' }}>
                                3-30 characters, letters, numbers, underscores. Can change once per 30 days.
                            </p>
                            <div style={{ display: 'flex', gap: '0.5rem' }}>
                                <button onClick={updateUsername} className="btn btn-primary" style={{ fontSize: '14px', padding: '0.5rem 1rem' }}>
                                    Save
                                </button>
                                <button
                                    onClick={() => {
                                        setEditing({ ...editing, username: false });
                                        setFormData({ ...formData, username: profile.username || '' });
                                        setError('');
                                    }}
                                    className="btn btn-secondary"
                                    style={{ fontSize: '14px', padding: '0.5rem 1rem' }}
                                >
                                    Cancel
                                </button>
                            </div>
                        </div>
                    ) : (
                        <div style={{ fontSize: '20px', fontWeight: '600' }}>
                            {profile.username ? `@${profile.username}` : (
                                <span style={{ color: 'var(--text-tertiary)', fontSize: '16px' }}>
                                    Not set - Click Edit to choose
                                </span>
                            )}
                        </div>
                    )}
                </div>

                {/* Share Code Section */}
                <div style={{ marginBottom: '1.5rem', padding: '1rem', background: 'var(--secondary-bg)', borderRadius: '8px' }}>
                    <label style={{ fontSize: '13px', fontWeight: '600', color: 'var(--text-secondary)', display: 'block', marginBottom: '0.5rem' }}>
                        SHARE CODE
                    </label>
                    <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap' }}>
                        <div style={{
                            fontSize: '24px',
                            fontWeight: '700',
                            fontFamily: 'monospace',
                            letterSpacing: '2px',
                            padding: '0.5rem 1rem',
                            background: 'var(--card-bg)',
                            borderRadius: '8px',
                            border: '2px dashed var(--primary)'
                        }}>
                            NV-{profile.share_code}
                        </div>
                        <button
                            onClick={() => copyToClipboard(`NV-${profile.share_code}`, 'Share code')}
                            className="btn btn-secondary"
                            style={{ fontSize: '14px', padding: '0.5rem 1rem' }}
                        >
                            📋 Copy
                        </button>
                        <button
                            onClick={regenerateShareCode}
                            className="btn btn-secondary"
                            style={{ fontSize: '14px', padding: '0.5rem 1rem' }}
                        >
                            🔄 New
                        </button>
                    </div>
                    <p style={{ fontSize: '12px', color: 'var(--text-tertiary)', marginTop: '0.5rem' }}>
                        Share this code for quick connections.
                    </p>
                </div>

                {/* Profile Link Section */}
                {profile.username && (
                    <div style={{ padding: '1rem', background: 'var(--secondary-bg)', borderRadius: '8px' }}>
                        <label style={{ fontSize: '13px', fontWeight: '600', color: 'var(--text-secondary)', display: 'block', marginBottom: '0.5rem' }}>
                            PROFILE LINK
                        </label>
                        <div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center' }}>
                            <input
                                readOnly
                                value={profileLink}
                                className="form-input"
                                style={{ flex: 1, padding: '0.5rem', fontSize: '14px', fontFamily: 'monospace' }}
                            />
                            <button
                                onClick={() => copyToClipboard(profileLink, 'Profile link')}
                                className="btn btn-primary"
                                style={{ fontSize: '14px', padding: '0.5rem 1rem', whiteSpace: 'nowrap' }}
                            >
                                📋 Copy
                            </button>
                        </div>
                    </div>
                )}
            </div>

            {/* Bio Card */}
            <div className="card" style={{ padding: '2rem' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
                    <h3 style={{ fontSize: '18px', fontWeight: '600' }}>📝 Bio</h3>
                    {!editing.bio && (
                        <button
                            onClick={() => setEditing({ ...editing, bio: true })}
                            style={{
                                padding: '0.25rem 0.75rem',
                                fontSize: '12px',
                                background: 'none',
                                border: '1px solid var(--border-color)',
                                borderRadius: '6px',
                                cursor: 'pointer'
                            }}
                        >
                            ✏️ Edit
                        </button>
                    )}
                </div>

                {editing.bio ? (
                    <div>
                        <textarea
                            value={formData.bio}
                            onChange={(e) => setFormData({ ...formData, bio: e.target.value })}
                            placeholder="Tell us about yourself..."
                            className="form-input"
                            style={{
                                width: '100%',
                                minHeight: '100px',
                                padding: '0.75rem',
                                fontSize: '14px',
                                resize: 'vertical',
                                marginBottom: '0.75rem'
                            }}
                            maxLength={500}
                        />
                        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                            <span style={{ fontSize: '12px', color: 'var(--text-tertiary)' }}>
                                {formData.bio.length}/500 characters
                            </span>
                            <div style={{ display: 'flex', gap: '0.5rem' }}>
                                <button onClick={updateBio} className="btn btn-primary" style={{ fontSize: '14px', padding: '0.5rem 1rem' }}>
                                    Save
                                </button>
                                <button
                                    onClick={() => {
                                        setEditing({ ...editing, bio: false });
                                        setFormData({ ...formData, bio: profile.bio || '' });
                                        setError('');
                                    }}
                                    className="btn btn-secondary"
                                    style={{ fontSize: '14px', padding: '0.5rem 1rem' }}
                                >
                                    Cancel
                                </button>
                            </div>
                        </div>
                    </div>
                ) : (
                    <p style={{ fontSize: '14px', color: 'var(--text-secondary)', lineHeight: '1.6', whiteSpace: 'pre-wrap' }}>
                        {profile.bio || 'No bio yet. Click Edit to add one.'}
                    </p>
                )}
            </div>

            {/* Friends Section */}
            <div className="card" style={{ padding: '2rem' }}>
                <h3 style={{ fontSize: '18px', fontWeight: '600', marginBottom: '1.5rem' }}>
                    👥 Friends ({friends.length})
                </h3>

                {friendsLoading ? (
                    <div style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-secondary)' }}>
                        Loading friends...
                    </div>
                ) : friends.length > 0 ? (
                    <div style={{
                        display: 'grid',
                        gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))',
                        gap: '1rem'
                    }}>
                        {friends.map(friend => (
                            <div
                                key={friend.id}
                                style={{
                                    padding: '1rem',
                                    background: 'var(--secondary-bg)',
                                    borderRadius: '12px',
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '0.75rem',
                                    transition: 'transform 0.2s',
                                    cursor: 'pointer'
                                }}
                                onMouseEnter={(e) => e.currentTarget.style.transform = 'scale(1.02)'}
                                onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
                            >
                                <div style={{
                                    width: '40px',
                                    height: '40px',
                                    borderRadius: '50%',
                                    background: friend.photo_url ? `url(${friend.photo_url})` : 'linear-gradient(135deg, var(--primary), var(--secondary, #6366f1))',
                                    backgroundSize: 'cover',
                                    backgroundPosition: 'center',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    fontSize: '16px',
                                    fontWeight: '700',
                                    color: 'white'
                                }}>
                                    {!friend.photo_url && (friend.name?.charAt(0).toUpperCase() || '?')}
                                </div>
                                <div style={{ flex: 1, minWidth: 0 }}>
                                    <div style={{
                                        fontWeight: '600',
                                        fontSize: '14px',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'
                                    }}>
                                        {friend.name}
                                    </div>
                                    <div style={{
                                        fontSize: '12px',
                                        color: 'var(--text-secondary)',
                                        overflow: 'hidden',
                                        textOverflow: 'ellipsis',
                                        whiteSpace: 'nowrap'
                                    }}>
                                        {friend.username ? `@${friend.username}` : `NV-${friend.share_code}`}
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                ) : (
                    <div style={{ textAlign: 'center', padding: '2rem' }}>
                        <div style={{ fontSize: '48px', marginBottom: '1rem' }}>👋</div>
                        <p style={{ color: 'var(--text-secondary)', marginBottom: '1rem' }}>
                            You haven't added any friends yet
                        </p>
                        <p style={{ fontSize: '14px', color: 'var(--text-tertiary)' }}>
                            Go to Share → Find People to discover and add friends
                        </p>
                    </div>
                )}
            </div>
        </div>
    );
}

window.ProfileView = ProfileView;
