import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useQuery, useConvex } from 'convex/react';
import { api } from '../../../../convex/_generated/api';
import { AllEmojis } from '../assets/emojis';
import AvatarCropModal from './AvatarCropModal';
import Cropper from 'react-easy-crop';

function getCroppedEmojiImg(imageSrc, pixelCrop, rotation, flipH, flipV) {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.crossOrigin = 'anonymous';
    image.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = 128;
      canvas.height = 128;
      const ctx = canvas.getContext('2d');

      ctx.translate(64, 64);
      ctx.rotate((rotation * Math.PI) / 180);
      ctx.scale(flipH ? -1 : 1, flipV ? -1 : 1);
      ctx.translate(-64, -64);

      ctx.drawImage(
        image,
        pixelCrop.x, pixelCrop.y, pixelCrop.width, pixelCrop.height,
        0, 0, 128, 128
      );
      canvas.toBlob((blob) => {
        if (!blob) return reject(new Error('Canvas toBlob failed'));
        resolve(blob);
      }, 'image/png');
    };
    image.onerror = reject;
    image.src = imageSrc;
  });
}

const TIMEOUT_OPTIONS = [
    { value: 60, label: '1 min' },
    { value: 300, label: '5 min' },
    { value: 900, label: '15 min' },
    { value: 1800, label: '30 min' },
    { value: 3600, label: '1 hour' },
];

const ServerSettingsModal = ({ onClose }) => {
    const [activeTab, setActiveTab] = useState('Overview');
    const [selectedRole, setSelectedRole] = useState(null);

    const userId = localStorage.getItem('userId');
    const convex = useConvex();

    // Reactive queries from Convex
    const roles = useQuery(api.roles.list) || [];
    const members = useQuery(api.roles.listMembers) || [];
    const myPermissions = useQuery(
        api.roles.getMyPermissions,
        userId ? { userId } : "skip"
    ) || {};

    // Custom emojis
    const customEmojis = useQuery(api.customEmojis.list) || [];
    const [showEmojiModal, setShowEmojiModal] = useState(false);
    const [emojiPreviewUrl, setEmojiPreviewUrl] = useState(null);
    const [emojiName, setEmojiName] = useState('');
    const [emojiFile, setEmojiFile] = useState(null);
    const [emojiUploading, setEmojiUploading] = useState(false);
    const [emojiError, setEmojiError] = useState('');
    const emojiFileInputRef = useRef(null);
    const [emojiCrop, setEmojiCrop] = useState({ x: 0, y: 0 });
    const [emojiZoom, setEmojiZoom] = useState(1);
    const [emojiRotation, setEmojiRotation] = useState(0);
    const [emojiFlipH, setEmojiFlipH] = useState(false);
    const [emojiFlipV, setEmojiFlipV] = useState(false);
    const [emojiCroppedAreaPixels, setEmojiCroppedAreaPixels] = useState(null);

    const onEmojiCropComplete = useCallback((_croppedArea, croppedPixels) => {
        setEmojiCroppedAreaPixels(croppedPixels);
    }, []);

    // Server settings
    const serverSettings = useQuery(api.serverSettings.get);
    const channels = useQuery(api.channels.list) || [];
    const voiceChannels = channels.filter(c => c.type === 'voice');
    const [serverName, setServerName] = useState('Secure Chat');
    const [serverNameDirty, setServerNameDirty] = useState(false);
    const [afkChannelId, setAfkChannelId] = useState('');
    const [afkTimeout, setAfkTimeout] = useState(300);
    const [afkDirty, setAfkDirty] = useState(false);
    const [iconFile, setIconFile] = useState(null);
    const [iconPreview, setIconPreview] = useState(null);
    const [rawIconUrl, setRawIconUrl] = useState(null);
    const [showIconCropModal, setShowIconCropModal] = useState(false);
    const [iconDirty, setIconDirty] = useState(false);
    const [savingIcon, setSavingIcon] = useState(false);
    const iconInputRef = useRef(null);

    useEffect(() => {
        const handleKey = (e) => {
            if (e.key === 'Escape') {
                if (showEmojiModal) {
                    handleEmojiModalClose();
                } else if (!showIconCropModal) {
                    onClose();
                }
            }
        };
        window.addEventListener('keydown', handleKey);
        return () => window.removeEventListener('keydown', handleKey);
    }, [onClose, showEmojiModal, showIconCropModal]);

    React.useEffect(() => {
        if (serverSettings) {
            setServerName(serverSettings.serverName || 'Secure Chat');
            setServerNameDirty(false);
            setAfkChannelId(serverSettings.afkChannelId || '');
            setAfkTimeout(serverSettings.afkTimeout || 300);
            setAfkDirty(false);
        }
    }, [serverSettings]);

    const handleSaveServerName = async () => {
        if (!userId) return;
        try {
            await convex.mutation(api.serverSettings.updateName, {
                userId,
                serverName,
            });
            setServerNameDirty(false);
        } catch (e) {
            console.error('Failed to update server name:', e);
            alert('Failed to save server name: ' + e.message);
        }
    };

    const handleSaveAfkSettings = async () => {
        if (!userId) return;
        try {
            await convex.mutation(api.serverSettings.update, {
                userId,
                afkChannelId: afkChannelId || undefined,
                afkTimeout,
            });
            setAfkDirty(false);
        } catch (e) {
            console.error('Failed to update server settings:', e);
            alert('Failed to save settings: ' + e.message);
        }
    };

    const handleIconFileChange = (e) => {
        const file = e.target.files?.[0];
        if (!file) return;
        const url = URL.createObjectURL(file);
        setRawIconUrl(url);
        setShowIconCropModal(true);
        e.target.value = '';
    };

    const handleIconCropApply = (blob) => {
        const file = new File([blob], 'server-icon.png', { type: 'image/png' });
        setIconFile(file);
        const previewUrl = URL.createObjectURL(blob);
        setIconPreview(previewUrl);
        if (rawIconUrl) URL.revokeObjectURL(rawIconUrl);
        setRawIconUrl(null);
        setShowIconCropModal(false);
        setIconDirty(true);
    };

    const handleIconCropCancel = () => {
        if (rawIconUrl) URL.revokeObjectURL(rawIconUrl);
        setRawIconUrl(null);
        setShowIconCropModal(false);
    };

    const handleSaveIcon = async () => {
        if (!userId || savingIcon) return;
        setSavingIcon(true);
        try {
            let iconStorageId;
            if (iconFile) {
                const uploadUrl = await convex.mutation(api.files.generateUploadUrl);
                const res = await fetch(uploadUrl, {
                    method: 'POST',
                    headers: { 'Content-Type': iconFile.type },
                    body: iconFile,
                });
                const { storageId } = await res.json();
                iconStorageId = storageId;
            }
            await convex.mutation(api.serverSettings.updateIcon, {
                userId,
                iconStorageId,
            });
            setIconFile(null);
            setIconDirty(false);
            if (iconPreview) {
                URL.revokeObjectURL(iconPreview);
                setIconPreview(null);
            }
        } catch (e) {
            console.error('Failed to update server icon:', e);
            alert('Failed to save server icon: ' + e.message);
        } finally {
            setSavingIcon(false);
        }
    };

    const handleRemoveIcon = async () => {
        if (!userId) return;
        setSavingIcon(true);
        try {
            await convex.mutation(api.serverSettings.updateIcon, {
                userId,
                iconStorageId: undefined,
            });
            setIconFile(null);
            setIconDirty(false);
            if (iconPreview) {
                URL.revokeObjectURL(iconPreview);
                setIconPreview(null);
            }
        } catch (e) {
            console.error('Failed to remove server icon:', e);
            alert('Failed to remove server icon: ' + e.message);
        } finally {
            setSavingIcon(false);
        }
    };

    const currentIconUrl = iconPreview || serverSettings?.iconUrl;

    const handleEmojiFileSelect = (e) => {
        const file = e.target.files?.[0];
        if (!file) return;
        const name = file.name.replace(/\.[^.]+$/, '').replace(/[^a-zA-Z0-9_]/g, '_').replace(/^_+|_+$/g, '').substring(0, 32);
        setEmojiFile(file);
        setEmojiName(name || 'emoji');
        setEmojiPreviewUrl(URL.createObjectURL(file));
        setEmojiError('');
        setShowEmojiModal(true);
        e.target.value = '';
    };

    const handleEmojiModalClose = () => {
        setShowEmojiModal(false);
        if (emojiPreviewUrl) URL.revokeObjectURL(emojiPreviewUrl);
        setEmojiPreviewUrl(null);
        setEmojiFile(null);
        setEmojiName('');
        setEmojiError('');
        setEmojiCrop({ x: 0, y: 0 });
        setEmojiZoom(1);
        setEmojiRotation(0);
        setEmojiFlipH(false);
        setEmojiFlipV(false);
        setEmojiCroppedAreaPixels(null);
    };

    const handleEmojiUpload = async () => {
        if (!userId || !emojiFile || !emojiName.trim()) return;
        setEmojiError('');
        const name = emojiName.trim();

        if (!/^[a-zA-Z0-9_]+$/.test(name)) {
            setEmojiError('Name can only contain letters, numbers, and underscores');
            return;
        }
        if (name.length < 2 || name.length > 32) {
            setEmojiError('Name must be between 2 and 32 characters');
            return;
        }
        if (AllEmojis.find(e => e.name === name)) {
            setEmojiError(`"${name}" conflicts with a built-in emoji`);
            return;
        }
        if (customEmojis.find(e => e.name === name)) {
            setEmojiError(`"${name}" already exists as a custom emoji`);
            return;
        }

        setEmojiUploading(true);
        try {
            let fileToUpload = emojiFile;
            if (emojiCroppedAreaPixels && emojiPreviewUrl) {
                const blob = await getCroppedEmojiImg(emojiPreviewUrl, emojiCroppedAreaPixels, emojiRotation, emojiFlipH, emojiFlipV);
                fileToUpload = new File([blob], 'emoji.png', { type: 'image/png' });
            }
            const uploadUrl = await convex.mutation(api.files.generateUploadUrl);
            const res = await fetch(uploadUrl, {
                method: 'POST',
                headers: { 'Content-Type': fileToUpload.type },
                body: fileToUpload,
            });
            const { storageId } = await res.json();
            await convex.mutation(api.customEmojis.upload, { userId, name, storageId });
            handleEmojiModalClose();
        } catch (e) {
            console.error('Failed to upload emoji:', e);
            setEmojiError(e.message || 'Failed to upload emoji');
        } finally {
            setEmojiUploading(false);
        }
    };

    const handleEmojiDelete = async (emojiId) => {
        if (!userId) return;
        try {
            await convex.mutation(api.customEmojis.remove, { userId, emojiId });
        } catch (e) {
            console.error('Failed to delete emoji:', e);
        }
    };

    const handleCreateRole = async () => {
        try {
            const newRole = await convex.mutation(api.roles.create, {
                name: 'new role',
                color: '#99aab5'
            });
            setSelectedRole(newRole);
        } catch (e) {
            console.error('Failed to create role:', e);
        }
    };

    const handleUpdateRole = async (id, updates) => {
        try {
            const updated = await convex.mutation(api.roles.update, { id, ...updates });
            if (selectedRole && selectedRole._id === id) {
                setSelectedRole(updated);
            }
        } catch (e) {
            console.error('Failed to update role:', e);
        }
    };

    const handleDeleteRole = async (id) => {
        if (!confirm('Delete this role?')) return;
        try {
            await convex.mutation(api.roles.remove, { id });
            if (selectedRole && selectedRole._id === id) setSelectedRole(null);
        } catch (e) {
            console.error('Failed to delete role:', e);
        }
    };

    const handleAssignRole = async (roleId, targetUserId, isAdding) => {
        const action = isAdding ? api.roles.assign : api.roles.unassign;
        try {
            await convex.mutation(action, { roleId, userId: targetUserId });
        } catch (e) {
            console.error('Failed to assign/unassign role:', e);
        }
    };

    // Render Tabs
    const renderSidebar = () => (
        <div style={{
            width: '218px',
            backgroundColor: 'var(--bg-secondary)',
            display: 'flex', flexDirection: 'column', alignItems: 'flex-end', padding: '60px 6px 60px 20px'
        }}>
            <div style={{ width: '100%', padding: '0 10px' }}>
                <div style={{ fontSize: '12px', fontWeight: '700', color: 'var(--text-muted)', marginBottom: '6px', textTransform: 'uppercase' }}>
                    Server Settings
                </div>
                {['Overview', 'Emoji', 'Roles', 'Members'].map(tab => (
                    <div
                        key={tab}
                        onClick={() => setActiveTab(tab)}
                        style={{
                            padding: '6px 10px', borderRadius: '4px',
                            backgroundColor: activeTab === tab ? 'var(--background-modifier-selected)' : 'transparent',
                            color: activeTab === tab ? 'var(--header-primary)' : 'var(--header-secondary)',
                            cursor: 'pointer', marginBottom: '2px', fontSize: '15px'
                        }}
                    >
                        {tab}
                    </div>
                ))}
            </div>
        </div>
    );

    const canManageRoles = myPermissions.manage_roles;
    const disabledOpacity = canManageRoles ? 1 : 0.5;
    const labelStyle = { display: 'block', color: 'var(--header-secondary)', fontSize: '12px', fontWeight: '700', marginBottom: 8 };
    const editableRoles = roles.filter(r => r.name !== 'Owner');

    const renderRolesTab = () => (
        <div style={{ display: 'flex', height: '100%' }}>
            <div style={{ width: '200px', borderRight: '1px solid var(--border-subtle)', marginRight: '20px' }}>
                 <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '10px' }}>
                    <h3 style={{ color: 'var(--header-secondary)', fontSize: '12px' }}>ROLES</h3>
                    {canManageRoles && (
                        <button onClick={handleCreateRole} style={{ background: 'transparent', border: 'none', color: 'var(--header-secondary)', cursor: 'pointer' }}>+</button>
                    )}
                 </div>
                 {editableRoles.map(r => (
                     <div
                        key={r._id}
                        onClick={() => setSelectedRole(r)}
                        style={{
                            padding: '6px',
                            backgroundColor: selectedRole?._id === r._id ? 'var(--background-modifier-selected)' : 'transparent',
                            borderRadius: '4px', cursor: 'pointer', color: r.color || '#b9bbbe',
                            display: 'flex', alignItems: 'center'
                        }}
                     >
                        <div style={{ width: 12, height: 12, borderRadius: '50%', background: r.color, marginRight: 8 }}></div>
                        {r.name}
                     </div>
                 ))}
            </div>

            {selectedRole ? (
                <div className="no-scrollbar" style={{ flex: 1, overflowY: 'auto' }}>
                    <h2 style={{ color: 'var(--header-primary)', marginTop: 0 }}>Edit Role - {selectedRole.name}</h2>

                    <label style={labelStyle}>ROLE NAME</label>
                    <input
                        value={selectedRole.name}
                        onChange={(e) => handleUpdateRole(selectedRole._id, { name: e.target.value })}
                        disabled={!canManageRoles}
                        style={{ width: '100%', padding: 10, background: 'var(--bg-tertiary)', border: 'none', borderRadius: 4, color: 'var(--header-primary)', marginBottom: 20, opacity: disabledOpacity }}
                    />

                    <label style={labelStyle}>ROLE COLOR</label>
                    <input
                        type="color"
                        value={selectedRole.color}
                        onChange={(e) => handleUpdateRole(selectedRole._id, { color: e.target.value })}
                        disabled={!canManageRoles}
                        style={{ width: '100%', height: 40, border: 'none', padding: 0, marginBottom: 20, opacity: disabledOpacity }}
                    />

                    <label style={labelStyle}>PERMISSIONS</label>
                    {['manage_channels', 'manage_roles', 'manage_nicknames', 'create_invite', 'embed_links', 'attach_files', 'move_members', 'mute_members'].map(perm => (
                        <div key={perm} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10, paddingBottom: 10, borderBottom: '1px solid var(--border-subtle)' }}>
                            <span style={{ color: 'var(--header-primary)', textTransform: 'capitalize' }}>{perm.replace('_', ' ')}</span>
                            <input
                                type="checkbox"
                                checked={selectedRole.permissions?.[perm] || false}
                                onChange={(e) => {
                                    handleUpdateRole(selectedRole._id, {
                                        permissions: { ...selectedRole.permissions, [perm]: e.target.checked }
                                    });
                                }}
                                disabled={!canManageRoles}
                                style={{ transform: 'scale(1.5)', opacity: disabledOpacity }}
                            />
                        </div>
                    ))}

                    {canManageRoles && selectedRole.name !== 'Owner' && selectedRole.name !== '@everyone' && (
                        <button onClick={() => handleDeleteRole(selectedRole._id)} style={{ color: '#ed4245', background: 'transparent', border: '1px solid #ed4245', padding: '6px 12px', borderRadius: 4, marginTop: 20, cursor: 'pointer' }}>
                            Delete Role
                        </button>
                    )}
                </div>
            ) : (
                <div style={{ color: 'var(--header-secondary)' }}>Select a role to edit</div>
            )}
        </div>
    );

    const renderMembersTab = () => (
        <div>
            <h2 style={{ color: 'var(--header-primary)' }}>Members</h2>
            {members.map(m => (
                <div key={m.id} style={{ display: 'flex', alignItems: 'center', padding: '10px', borderBottom: '1px solid var(--border-subtle)' }}>
                    <div style={{ width: 32, height: 32, borderRadius: '50%', background: '#5865F2', marginRight: 10, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--header-primary)' }}>
                        {m.username[0].toUpperCase()}
                    </div>
                    <div style={{ flex: 1 }}>
                        <div style={{ color: 'var(--header-primary)', fontWeight: 'bold' }}>{m.username}</div>
                        <div style={{ display: 'flex', gap: 4 }}>
                            {m.roles?.map(r => (
                                <span key={r._id} style={{ fontSize: 10, background: r.color, color: 'var(--header-primary)', padding: '2px 4px', borderRadius: 4 }}>
                                    {r.name}
                                </span>
                            ))}
                        </div>
                    </div>
                    {canManageRoles && (
                        <div style={{ display: 'flex', gap: 4 }}>
                            {editableRoles.map(r => {
                                const hasRole = m.roles?.some(ur => ur._id === r._id);
                                return (
                                    <button
                                        key={r._id}
                                        onClick={() => handleAssignRole(r._id, m.id, !hasRole)}
                                        style={{
                                            width: 16, height: 16, borderRadius: '50%',
                                            border: `2px solid ${r.color}`,
                                            background: hasRole ? r.color : 'transparent',
                                            cursor: 'pointer'
                                        }}
                                        title={hasRole ? `Remove ${r.name}` : `Add ${r.name}`}
                                    />
                                );
                            })}
                        </div>
                    )}
                </div>
            ))}
        </div>
    );

    const renderEmojiTab = () => (
        <div>
            <div style={{ marginBottom: 20 }}>
                <p style={{ color: 'var(--header-secondary)', fontSize: 14, margin: '0 0 16px' }}>
                    Add custom emoji that anyone can use in this server.
                </p>
                {myPermissions.manage_channels && (
                    <>
                        <button
                            onClick={() => emojiFileInputRef.current?.click()}
                            style={{
                                backgroundColor: '#5865F2', color: '#fff', border: 'none',
                                borderRadius: 3, padding: '8px 16px', cursor: 'pointer',
                                fontWeight: 600, fontSize: 14,
                            }}
                        >
                            Upload Emoji
                        </button>
                        <input
                            ref={emojiFileInputRef}
                            type="file"
                            accept="image/*,.gif"
                            onChange={handleEmojiFileSelect}
                            style={{ display: 'none' }}
                        />
                    </>
                )}
            </div>

            {/* Emoji table */}
            <div style={{ borderTop: '1px solid var(--border-subtle)' }}>
                {/* Table header */}
                <div style={{
                    display: 'grid', gridTemplateColumns: '48px 1fr 1fr 40px',
                    padding: '8px 12px', alignItems: 'center',
                    borderBottom: '1px solid var(--border-subtle)',
                }}>
                    <span style={{ color: 'var(--header-secondary)', fontSize: 12, fontWeight: 700, textTransform: 'uppercase' }}>Image</span>
                    <span style={{ color: 'var(--header-secondary)', fontSize: 12, fontWeight: 700, textTransform: 'uppercase' }}>Name</span>
                    <span style={{ color: 'var(--header-secondary)', fontSize: 12, fontWeight: 700, textTransform: 'uppercase' }}>Uploaded By</span>
                    <span />
                </div>

                {customEmojis.length === 0 ? (
                    <div style={{ color: 'var(--header-secondary)', textAlign: 'center', padding: '40px 0' }}>
                        No custom emojis yet
                    </div>
                ) : (
                    customEmojis.map(emoji => (
                        <div
                            key={emoji._id}
                            className="emoji-table-row"
                            style={{
                                display: 'grid', gridTemplateColumns: '48px 1fr 1fr 40px',
                                padding: '8px 12px', alignItems: 'center',
                                borderBottom: '1px solid var(--border-subtle)',
                            }}
                        >
                            <img src={emoji.src} alt={emoji.name} style={{ width: 32, height: 32, objectFit: 'contain' }} />
                            <span style={{ color: 'var(--header-primary)', fontSize: 15 }}>:{emoji.name}:</span>
                            <span style={{ color: 'var(--header-secondary)', fontSize: 14 }}>{emoji.uploadedByUsername}</span>
                            <div style={{ display: 'flex', justifyContent: 'center' }}>
                                {myPermissions.manage_channels && (
                                    <button
                                        onClick={() => handleEmojiDelete(emoji._id)}
                                        style={{
                                            background: 'transparent', border: 'none', color: 'var(--header-secondary)',
                                            cursor: 'pointer', fontSize: 16, padding: '4px 8px',
                                            borderRadius: 4, opacity: 0.5, transition: 'opacity 0.15s, color 0.15s',
                                        }}
                                        onMouseEnter={(e) => { e.currentTarget.style.opacity = '1'; e.currentTarget.style.color = '#ed4245'; }}
                                        onMouseLeave={(e) => { e.currentTarget.style.opacity = '0.5'; e.currentTarget.style.color = 'var(--header-secondary)'; }}
                                        title="Delete emoji"
                                    >
                                        ✕
                                    </button>
                                )}
                            </div>
                        </div>
                    ))
                )}
            </div>
        </div>
    );

    const renderTabContent = () => {
        switch (activeTab) {
            case 'Emoji': return renderEmojiTab();
            case 'Roles': return renderRolesTab();
            case 'Members': return renderMembersTab();
            default: return (
                <div>
                    <label style={labelStyle}>SERVER ICON</label>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '16px', marginBottom: 20 }}>
                        <div
                            className="server-icon-upload-wrapper"
                            onClick={() => myPermissions.manage_channels && iconInputRef.current?.click()}
                            style={{ cursor: myPermissions.manage_channels ? 'pointer' : 'default', opacity: myPermissions.manage_channels ? 1 : 0.5 }}
                        >
                            {currentIconUrl ? (
                                <img src={currentIconUrl} alt="Server Icon" style={{ width: 80, height: 80, objectFit: 'cover', borderRadius: '16px' }} />
                            ) : (
                                <div style={{
                                    width: 80, height: 80, borderRadius: '16px',
                                    backgroundColor: 'var(--bg-tertiary)',
                                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                                    color: 'var(--text-normal)', fontWeight: 600, fontSize: '24px',
                                }}>
                                    {serverName.substring(0, 2)}
                                </div>
                            )}
                            {myPermissions.manage_channels && (
                                <div className="server-icon-upload-overlay">
                                    CHANGE<br/>ICON
                                </div>
                            )}
                            <input
                                ref={iconInputRef}
                                type="file"
                                accept="image/*"
                                onChange={handleIconFileChange}
                                style={{ display: 'none' }}
                            />
                        </div>
                        <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                            {iconDirty && myPermissions.manage_channels && (
                                <button
                                    onClick={handleSaveIcon}
                                    disabled={savingIcon}
                                    style={{
                                        backgroundColor: '#5865F2', color: '#fff', border: 'none',
                                        borderRadius: 4, padding: '8px 16px', cursor: savingIcon ? 'not-allowed' : 'pointer',
                                        fontWeight: 600, fontSize: 14, opacity: savingIcon ? 0.5 : 1,
                                    }}
                                >
                                    {savingIcon ? 'Saving...' : 'Upload Icon'}
                                </button>
                            )}
                            {currentIconUrl && !iconDirty && myPermissions.manage_channels && (
                                <button
                                    onClick={handleRemoveIcon}
                                    disabled={savingIcon}
                                    style={{
                                        backgroundColor: 'transparent', color: '#ed4245', border: '1px solid #ed4245',
                                        borderRadius: 4, padding: '6px 12px', cursor: 'pointer',
                                        fontWeight: 600, fontSize: 13,
                                    }}
                                >
                                    Remove Icon
                                </button>
                            )}
                        </div>
                    </div>

                    <label style={labelStyle}>SERVER NAME</label>
                    <input
                        value={serverName}
                        onChange={(e) => { setServerName(e.target.value); setServerNameDirty(true); }}
                        disabled={!myPermissions.manage_channels}
                        maxLength={100}
                        style={{
                            width: '100%', padding: 10, background: 'var(--bg-tertiary)', border: 'none',
                            borderRadius: 4, color: 'var(--header-primary)', marginBottom: 8,
                            opacity: myPermissions.manage_channels ? 1 : 0.5,
                        }}
                    />
                    {serverNameDirty && myPermissions.manage_channels && (
                        <button
                            onClick={handleSaveServerName}
                            disabled={!serverName.trim()}
                            style={{
                                backgroundColor: '#5865F2', color: '#fff', border: 'none',
                                borderRadius: 4, padding: '8px 16px', cursor: 'pointer',
                                fontWeight: 600, fontSize: 14, marginBottom: 20,
                                opacity: serverName.trim() ? 1 : 0.5,
                            }}
                        >
                            Save Changes
                        </button>
                    )}
                    {!serverNameDirty && <div style={{ marginBottom: 12 }} />}

                    <div style={{ color: 'var(--header-secondary)', marginBottom: 20, fontSize: '14px' }}>Region: US-East</div>

                    <label style={labelStyle}>INACTIVE CHANNEL</label>
                    <select
                        value={afkChannelId}
                        onChange={(e) => { setAfkChannelId(e.target.value); setAfkDirty(true); }}
                        disabled={!myPermissions.manage_channels}
                        style={{
                            width: '100%', padding: 10, background: 'var(--bg-tertiary)', border: 'none',
                            borderRadius: 4, color: 'var(--header-primary)', marginBottom: 20,
                            opacity: myPermissions.manage_channels ? 1 : 0.5, cursor: 'pointer',
                            appearance: 'auto',
                        }}
                    >
                        <option value="">No Inactive Channel</option>
                        {voiceChannels.map(ch => (
                            <option key={ch._id} value={ch._id}>{ch.name}</option>
                        ))}
                    </select>

                    <label style={labelStyle}>INACTIVE TIMEOUT</label>
                    <select
                        value={afkTimeout}
                        onChange={(e) => { setAfkTimeout(Number(e.target.value)); setAfkDirty(true); }}
                        disabled={!myPermissions.manage_channels}
                        style={{
                            width: '100%', padding: 10, background: 'var(--bg-tertiary)', border: 'none',
                            borderRadius: 4, color: 'var(--header-primary)', marginBottom: 20,
                            opacity: myPermissions.manage_channels ? 1 : 0.5, cursor: 'pointer',
                            appearance: 'auto',
                        }}
                    >
                        {TIMEOUT_OPTIONS.map(opt => (
                            <option key={opt.value} value={opt.value}>{opt.label}</option>
                        ))}
                    </select>

                    {afkDirty && myPermissions.manage_channels && (
                        <button
                            onClick={handleSaveAfkSettings}
                            style={{
                                backgroundColor: '#5865F2', color: '#fff', border: 'none',
                                borderRadius: 4, padding: '8px 16px', cursor: 'pointer',
                                fontWeight: 600, fontSize: 14,
                            }}
                        >
                            Save Changes
                        </button>
                    )}
                </div>
            );
        }
    };

    return (
        <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'var(--bg-primary)', zIndex: 1000, display: 'flex', color: 'var(--text-normal)' }}>
            {renderSidebar()}
            <div style={{ flex: 1, display: 'flex', justifyContent: 'flex-start', overflowY: 'auto' }}>
                <div style={{ flex: 1, maxWidth: '740px', padding: '60px 40px 80px', position: 'relative' }}>
                    <h2 style={{ color: 'var(--header-primary)', margin: 0, marginBottom: 20 }}>{activeTab}</h2>
                    {renderTabContent()}
                </div>
                <div style={{ flex: '0 0 36px', paddingTop: '60px', marginLeft: '8px' }}>
                    <button
                        onClick={onClose}
                        style={{
                            width: '36px', height: '36px', borderRadius: '50%',
                            border: '2px solid var(--header-secondary)', background: 'transparent',
                            color: 'var(--header-secondary)', cursor: 'pointer',
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            fontSize: '18px',
                        }}
                    >
                        ✕
                    </button>
                    <div style={{ fontSize: '13px', fontWeight: '600', color: 'var(--header-secondary)', textAlign: 'center', marginTop: '4px' }}>
                        ESC
                    </div>
                </div>
                <div style={{ flex: '0.5' }} />
            </div>
            {showIconCropModal && rawIconUrl && (
                <AvatarCropModal
                    imageUrl={rawIconUrl}
                    onApply={handleIconCropApply}
                    onCancel={handleIconCropCancel}
                    cropShape="rect"
                />
            )}
            {showEmojiModal && emojiPreviewUrl && (
                <div
                    onClick={handleEmojiModalClose}
                    style={{
                        position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
                        backgroundColor: 'rgba(0,0,0,0.7)', zIndex: 2000,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}
                >
                    <div
                        onClick={(e) => e.stopPropagation()}
                        style={{
                            backgroundColor: 'var(--bg-secondary)', borderRadius: 8,
                            width: 580, maxWidth: '90vw', overflow: 'hidden',
                        }}
                    >
                        {/* Modal header */}
                        <div style={{
                            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                            padding: '16px 16px 0',
                        }}>
                            <h2 style={{ color: 'var(--header-primary)', margin: 0, fontSize: 20, fontWeight: 600 }}>Add Emoji</h2>
                            <button
                                onClick={handleEmojiModalClose}
                                style={{
                                    background: 'transparent', border: 'none', color: 'var(--header-secondary)',
                                    cursor: 'pointer', fontSize: 20, padding: '4px 8px',
                                }}
                            >
                                ✕
                            </button>
                        </div>

                        {/* Modal body */}
                        <div style={{ display: 'flex', padding: '20px 16px 16px', gap: 24 }}>
                            {/* Left: Cropper + toolbar + zoom */}
                            <div style={{ width: 240, minWidth: 240, display: 'flex', flexDirection: 'column', gap: 10 }}>
                                <div style={{
                                    width: 240, height: 240, position: 'relative',
                                    backgroundColor: 'var(--bg-tertiary)', borderRadius: 8,
                                    overflow: 'hidden',
                                }}>
                                    <Cropper
                                        image={emojiPreviewUrl}
                                        crop={emojiCrop}
                                        zoom={emojiZoom}
                                        rotation={emojiRotation}
                                        aspect={1}
                                        cropShape="rect"
                                        showGrid={false}
                                        onCropChange={setEmojiCrop}
                                        onZoomChange={setEmojiZoom}
                                        onCropComplete={onEmojiCropComplete}
                                        style={{
                                            containerStyle: { width: 240, height: 240 },
                                            mediaStyle: {
                                                transform: `${emojiFlipH ? 'scaleX(-1)' : ''} ${emojiFlipV ? 'scaleY(-1)' : ''}`.trim() || undefined,
                                            },
                                        }}
                                    />
                                </div>

                                {/* Toolbar: rotate + flip */}
                                <div style={{ display: 'flex', justifyContent: 'center', gap: 4 }}>
                                    <button
                                        onClick={() => setEmojiRotation((r) => (r - 90 + 360) % 360)}
                                        title="Rotate left"
                                        style={{
                                            width: 36, height: 36, borderRadius: 4,
                                            background: 'var(--bg-tertiary)', border: 'none',
                                            color: 'var(--header-secondary)', cursor: 'pointer',
                                            fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center',
                                        }}
                                    >
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M7.11 8.53L5.7 7.11C4.8 8.27 4.24 9.61 4.07 11h2.02c.14-.87.49-1.72 1.02-2.47zM6.09 13H4.07c.17 1.39.72 2.73 1.62 3.89l1.41-1.42c-.52-.75-.87-1.59-1.01-2.47zm1.01 5.32c1.16.9 2.51 1.44 3.9 1.61V17.9c-.87-.15-1.71-.49-2.46-1.03L7.1 18.32zM13 4.07V1L8.45 5.55 13 10V6.09c2.84.48 5 2.94 5 5.91s-2.16 5.43-5 5.91v2.02c3.95-.49 7-3.85 7-7.93s-3.05-7.44-7-7.93z"/></svg>
                                    </button>
                                    <button
                                        onClick={() => setEmojiRotation((r) => (r + 90) % 360)}
                                        title="Rotate right"
                                        style={{
                                            width: 36, height: 36, borderRadius: 4,
                                            background: 'var(--bg-tertiary)', border: 'none',
                                            color: 'var(--header-secondary)', cursor: 'pointer',
                                            fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center',
                                        }}
                                    >
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style={{ transform: 'scaleX(-1)' }}><path d="M7.11 8.53L5.7 7.11C4.8 8.27 4.24 9.61 4.07 11h2.02c.14-.87.49-1.72 1.02-2.47zM6.09 13H4.07c.17 1.39.72 2.73 1.62 3.89l1.41-1.42c-.52-.75-.87-1.59-1.01-2.47zm1.01 5.32c1.16.9 2.51 1.44 3.9 1.61V17.9c-.87-.15-1.71-.49-2.46-1.03L7.1 18.32zM13 4.07V1L8.45 5.55 13 10V6.09c2.84.48 5 2.94 5 5.91s-2.16 5.43-5 5.91v2.02c3.95-.49 7-3.85 7-7.93s-3.05-7.44-7-7.93z"/></svg>
                                    </button>
                                    <button
                                        onClick={() => setEmojiFlipH((f) => !f)}
                                        title="Flip horizontal"
                                        style={{
                                            width: 36, height: 36, borderRadius: 4,
                                            background: emojiFlipH ? 'rgba(88, 101, 242, 0.3)' : 'var(--bg-tertiary)',
                                            border: emojiFlipH ? '1px solid #5865F2' : 'none',
                                            color: 'var(--header-secondary)', cursor: 'pointer',
                                            fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center',
                                        }}
                                    >
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M15 21h2v-2h-2v2zm4-12h2V7h-2v2zM3 5v14c0 1.1.9 2 2 2h4v-2H5V5h4V3H5c-1.1 0-2 .9-2 2zm16-2v2h2c0-1.1-.9-2-2-2zm-8-2h2v24h-2V1zm8 8h2v2h-2v-2zm0 8c1.1 0 2-.9 2-2h-2v2zm0-4h2v-2h-2v2zm-4 8h2v-2h-2v2zm4-16h2v-2h-2v2z"/></svg>
                                    </button>
                                    <button
                                        onClick={() => setEmojiFlipV((f) => !f)}
                                        title="Flip vertical"
                                        style={{
                                            width: 36, height: 36, borderRadius: 4,
                                            background: emojiFlipV ? 'rgba(88, 101, 242, 0.3)' : 'var(--bg-tertiary)',
                                            border: emojiFlipV ? '1px solid #5865F2' : 'none',
                                            color: 'var(--header-secondary)', cursor: 'pointer',
                                            fontSize: 16, display: 'flex', alignItems: 'center', justifyContent: 'center',
                                        }}
                                    >
                                        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" style={{ transform: 'rotate(90deg)' }}><path d="M15 21h2v-2h-2v2zm4-12h2V7h-2v2zM3 5v14c0 1.1.9 2 2 2h4v-2H5V5h4V3H5c-1.1 0-2 .9-2 2zm16-2v2h2c0-1.1-.9-2-2-2zm-8-2h2v24h-2V1zm8 8h2v2h-2v-2zm0 8c1.1 0 2-.9 2-2h-2v2zm0-4h2v-2h-2v2zm-4 8h2v-2h-2v2zm4-16h2v-2h-2v2z"/></svg>
                                    </button>
                                </div>

                                {/* Zoom slider */}
                                <div className="avatar-crop-slider-row" style={{ padding: 0, margin: 0 }}>
                                    <svg width="16" height="16" viewBox="0 0 24 24" fill="var(--header-secondary)">
                                        <path d="M15 3H9v2h6V3zm-4 18h2v-2h-2v2zm8-15.97l-1.41-1.41-1.76 1.76 1.41 1.41L19 5.03zM4.76 4.38L3.34 5.8 5.1 7.56 6.52 6.14 4.76 4.38zM21 11h-2v2h2v-2zM5 11H3v2h2v-2zm7-4a5 5 0 100 10 5 5 0 000-10z"/>
                                    </svg>
                                    <input
                                        type="range"
                                        min={1}
                                        max={3}
                                        step={0.01}
                                        value={emojiZoom}
                                        onChange={(e) => setEmojiZoom(Number(e.target.value))}
                                        className="avatar-crop-slider"
                                    />
                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="var(--header-secondary)">
                                        <path d="M15 3H9v2h6V3zm-4 18h2v-2h-2v2zm8-15.97l-1.41-1.41-1.76 1.76 1.41 1.41L19 5.03zM4.76 4.38L3.34 5.8 5.1 7.56 6.52 6.14 4.76 4.38zM21 11h-2v2h2v-2zM5 11H3v2h2v-2zm7-4a5 5 0 100 10 5 5 0 000-10z"/>
                                    </svg>
                                </div>
                            </div>

                            {/* Right: Reaction preview + Name + Finish */}
                            <div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
                                {/* Reaction pill preview */}
                                <div style={{ marginBottom: 16 }}>
                                    <span style={{ color: 'var(--header-secondary)', fontSize: 12, fontWeight: 700, textTransform: 'uppercase', display: 'block', marginBottom: 8 }}>
                                        Preview
                                    </span>
                                    <div style={{
                                        display: 'inline-flex', alignItems: 'center', gap: 4,
                                        backgroundColor: 'rgba(88, 101, 242, 0.15)',
                                        border: '1px solid var(--brand-experiment, #5865F2)',
                                        borderRadius: 8, padding: '2px 6px', cursor: 'default',
                                    }}>
                                        <img
                                            src={emojiPreviewUrl}
                                            alt=""
                                            style={{
                                                width: 16, height: 16, objectFit: 'contain',
                                                transform: `${emojiFlipH ? 'scaleX(-1)' : ''} ${emojiFlipV ? 'scaleY(-1)' : ''}`.trim() || undefined,
                                            }}
                                        />
                                        <span style={{ color: 'var(--text-normal)', fontSize: 14, marginLeft: 2 }}>1</span>
                                    </div>
                                </div>

                                {/* Emoji name input */}
                                <div style={{ marginBottom: 16 }}>
                                    <label style={{ color: 'var(--header-secondary)', fontSize: 12, fontWeight: 700, textTransform: 'uppercase', display: 'block', marginBottom: 8 }}>
                                        Emoji name <span style={{ color: '#ed4245' }}>*</span>
                                    </label>
                                    <div style={{ position: 'relative' }}>
                                        <input
                                            type="text"
                                            value={emojiName}
                                            onChange={(e) => { setEmojiName(e.target.value); setEmojiError(''); }}
                                            maxLength={32}
                                            style={{
                                                width: '100%', padding: '10px 32px 10px 10px',
                                                background: 'var(--bg-tertiary)', border: 'none',
                                                borderRadius: 4, color: 'var(--header-primary)', fontSize: 14,
                                                boxSizing: 'border-box',
                                            }}
                                        />
                                        {emojiName && (
                                            <button
                                                onClick={() => setEmojiName('')}
                                                style={{
                                                    position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)',
                                                    background: 'transparent', border: 'none', color: 'var(--header-secondary)',
                                                    cursor: 'pointer', fontSize: 14, padding: '2px 4px',
                                                }}
                                            >
                                                ✕
                                            </button>
                                        )}
                                    </div>
                                    {emojiError && (
                                        <div style={{ color: '#ed4245', fontSize: 13, marginTop: 6 }}>{emojiError}</div>
                                    )}
                                </div>

                                <div style={{ flex: 1 }} />

                                {/* Finish button */}
                                <button
                                    onClick={handleEmojiUpload}
                                    disabled={emojiUploading || !emojiName.trim()}
                                    style={{
                                        backgroundColor: '#5865F2', color: '#fff', border: 'none',
                                        borderRadius: 3, padding: '10px 0', cursor: emojiUploading ? 'not-allowed' : 'pointer',
                                        fontWeight: 600, fontSize: 14, width: '100%',
                                        opacity: (emojiUploading || !emojiName.trim()) ? 0.5 : 1,
                                    }}
                                >
                                    {emojiUploading ? 'Uploading...' : 'Finish'}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default ServerSettingsModal;
