import React, { useState, useEffect, useCallback } from 'react';
import { toast } from 'react-toastify';
import entraService from '../services/entraService';
import { useAuth } from '../context/AuthContext';

// ─── Hilfsfunktionen ─────────────────────────────────────────────────────────

const ROLE_RISK = {
    'Global Administrator':           'kritisch',
    'Privileged Role Administrator':  'kritisch',
    'Security Administrator':         'hoch',
    'Intune Administrator':           'hoch',
    'Exchange Administrator':         'hoch',
    'SharePoint Administrator':       'mittel',
    'Teams Administrator':            'mittel',
    'Helpdesk Administrator':         'mittel',
    'User Administrator':             'mittel',
    'Security Reader':                'niedrig',
    'Reports Reader':                 'niedrig',
    'Directory Readers':              'niedrig',
};

function getRoleRisk(name) {
    return ROLE_RISK[name] || 'niedrig';
}

const riskStyle = {
    kritisch: { bg: 'rgba(239,68,68,0.15)',  text: '#ef4444', border: '#ef4444' },
    hoch:     { bg: 'rgba(249,115,22,0.15)', text: '#f97316', border: '#f97316' },
    mittel:   { bg: 'rgba(245,158,11,0.15)', text: '#f59e0b', border: '#f59e0b' },
    niedrig:  { bg: 'rgba(34,197,94,0.15)',  text: '#22c55e', border: '#22c55e' },
};

const glass = {
    background: 'rgba(255,255,255,0.05)',
    border: '1px solid rgba(255,255,255,0.1)',
    borderRadius: 12,
    backdropFilter: 'blur(10px)',
};

function initials(name) {
    return (name || '?').split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase();
}

// ─── Komponenten ─────────────────────────────────────────────────────────────

function StatCard({ icon, label, value, sub, color }) {
    return (
        <div style={{ ...glass, padding: '20px 24px', flex: 1, minWidth: 160 }}>
            <div style={{ fontSize: 26, marginBottom: 6 }}>{icon}</div>
            <div style={{ fontSize: 28, fontWeight: 700, color: color || '#fff' }}>{value}</div>
            <div style={{ fontSize: 13, color: '#94a3b8', fontWeight: 600, marginTop: 2 }}>{label}</div>
            {sub && <div style={{ fontSize: 11, color: '#64748b', marginTop: 4 }}>{sub}</div>}
        </div>
    );
}

function Avatar({ name, size = 36 }) {
    return (
        <div style={{
            width: size, height: size, borderRadius: '50%', flexShrink: 0,
            background: 'linear-gradient(135deg, #6366f1, #8b5cf6)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: size * 0.35, fontWeight: 700, color: '#fff',
        }}>{initials(name)}</div>
    );
}

function GroupChip({ name }) {
    return (
        <span style={{
            display: 'inline-block', padding: '2px 8px', borderRadius: 12, marginRight: 4, marginBottom: 3,
            background: 'rgba(99,102,241,0.15)', color: '#a5b4fc',
            border: '1px solid rgba(99,102,241,0.3)', fontSize: 11,
        }}>{name}</span>
    );
}

// ─── User Detail Panel ────────────────────────────────────────────────────────

function UserDetailPanel({ user, onClose, onGroupRemove, onGroupAdd }) {
    const [groups, setGroups]       = useState([]);
    const [loadingGroups, setLoadingGroups] = useState(true);
    const [removingId, setRemovingId]       = useState(null);
    const [showGroupPicker, setShowGroupPicker] = useState(false);
    const [allGroups, setAllGroups] = useState([]);
    const [addingId, setAddingId]   = useState(null);

    useEffect(() => {
        if (!user) return;
        setLoadingGroups(true);
        setGroups([]);
        entraService.getUserGroups(user.id)
            .then(setGroups)
            .catch(() => toast.error('Gruppen konnten nicht geladen werden'))
            .finally(() => setLoadingGroups(false));
    }, [user]);

    const handleRemove = async (groupId, groupName) => {
        setRemovingId(groupId);
        try {
            await entraService.removeGroupMember(groupId, user.id);
            setGroups(g => g.filter(x => x.id !== groupId));
            toast.success(`Aus "${groupName}" entfernt`);
            onGroupRemove?.();
        } catch (e) {
            toast.error(e.response?.data?.message || e.message);
        } finally {
            setRemovingId(null);
        }
    };

    const openGroupPicker = async () => {
        if (allGroups.length === 0) {
            try { setAllGroups(await entraService.getGroups()); } catch { toast.error('Gruppen konnten nicht geladen werden'); }
        }
        setShowGroupPicker(true);
    };

    const handleAdd = async (group) => {
        setAddingId(group.id);
        try {
            await entraService.addGroupMember(group.id, user.id);
            setGroups(g => [...g, group]);
            setShowGroupPicker(false);
            toast.success(`Zu "${group.displayName}" hinzugefügt`);
            onGroupAdd?.();
        } catch (e) {
            toast.error(e.response?.data?.message || e.message);
        } finally {
            setAddingId(null);
        }
    };

    if (!user) return null;

    const groupIds = new Set(groups.map(g => g.id));
    const availableGroups = allGroups.filter(g => !groupIds.has(g.id));

    return (
        <div style={{
            position: 'fixed', top: 0, right: 0, bottom: 0, width: 400, zIndex: 200,
            background: 'rgba(10,15,30,0.97)', borderLeft: '1px solid rgba(255,255,255,0.1)',
            padding: 28, overflowY: 'auto', backdropFilter: 'blur(20px)',
        }}>
            {/* Header */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 22 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
                    <Avatar name={user.displayName} size={52} />
                    <div>
                        <div style={{ fontWeight: 700, fontSize: 16, color: '#f1f5f9' }}>{user.displayName}</div>
                        <div style={{ fontSize: 12, color: '#64748b' }}>{user.jobTitle || user.department || '—'}</div>
                    </div>
                </div>
                <button onClick={onClose} style={{ background: 'none', border: 'none', color: '#64748b', cursor: 'pointer', fontSize: 20 }}>✕</button>
            </div>

            {/* Status Badges */}
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 20 }}>
                <span style={{
                    padding: '4px 12px', borderRadius: 8, fontSize: 12, fontWeight: 600,
                    background: user.accountEnabled ? 'rgba(34,197,94,0.15)' : 'rgba(239,68,68,0.15)',
                    color: user.accountEnabled ? '#22c55e' : '#ef4444',
                    border: `1px solid ${user.accountEnabled ? 'rgba(34,197,94,0.3)' : 'rgba(239,68,68,0.3)'}`,
                }}>{user.accountEnabled ? '✓ Konto aktiv' : '✗ Deaktiviert'}</span>

                {user.mfaRegistered !== null && (
                    <span style={{
                        padding: '4px 12px', borderRadius: 8, fontSize: 12, fontWeight: 600,
                        background: user.mfaRegistered ? 'rgba(34,197,94,0.15)' : 'rgba(245,158,11,0.15)',
                        color: user.mfaRegistered ? '#22c55e' : '#f59e0b',
                        border: `1px solid ${user.mfaRegistered ? 'rgba(34,197,94,0.3)' : 'rgba(245,158,11,0.3)'}`,
                    }}>{user.mfaRegistered ? '🔐 MFA aktiv' : '⚠️ Kein MFA'}</span>
                )}
            </div>

            {/* E-Mail */}
            <div style={{ marginBottom: 18 }}>
                <div style={{ fontSize: 11, color: '#64748b', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 4 }}>E-Mail</div>
                <div style={{ fontSize: 13, color: '#94a3b8' }}>{user.mail}</div>
            </div>

            {/* MFA Methoden */}
            {user.mfaMethods?.length > 0 && (
                <div style={{ marginBottom: 18 }}>
                    <div style={{ fontSize: 11, color: '#64748b', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>MFA-Methoden</div>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                        {user.mfaMethods.map(m => (
                            <span key={m} style={{
                                padding: '3px 10px', borderRadius: 8, fontSize: 11,
                                background: 'rgba(99,102,241,0.12)', color: '#a5b4fc',
                                border: '1px solid rgba(99,102,241,0.25)',
                            }}>{m}</span>
                        ))}
                    </div>
                </div>
            )}

            {/* Gruppen */}
            <div style={{ marginBottom: 18 }}>
                <div style={{ fontSize: 11, color: '#64748b', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>
                    Gruppen {loadingGroups ? '…' : `(${groups.length})`}
                </div>
                {loadingGroups ? (
                    <div style={{ fontSize: 12, color: '#475569' }}>Wird geladen…</div>
                ) : (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                        {groups.map(g => (
                            <div key={g.id} style={{
                                display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                                padding: '7px 10px', borderRadius: 8,
                                background: 'rgba(99,102,241,0.08)', border: '1px solid rgba(99,102,241,0.2)',
                            }}>
                                <span style={{ fontSize: 12, color: '#a5b4fc' }}>👥 {g.displayName}</span>
                                <button
                                    onClick={() => handleRemove(g.id, g.displayName)}
                                    disabled={removingId === g.id}
                                    style={{ background: 'none', border: 'none', color: removingId === g.id ? '#475569' : '#ef4444', cursor: 'pointer', fontSize: 13 }}
                                >{removingId === g.id ? '…' : '✕'}</button>
                            </div>
                        ))}
                        {groups.length === 0 && <div style={{ fontSize: 12, color: '#475569' }}>Keine Gruppen</div>}
                    </div>
                )}
                <button onClick={openGroupPicker} style={{
                    marginTop: 10, padding: '7px 14px', borderRadius: 8, fontSize: 12, width: '100%',
                    background: 'rgba(99,102,241,0.1)', border: '1px dashed rgba(99,102,241,0.3)',
                    color: '#a5b4fc', cursor: 'pointer',
                }}>+ Gruppe hinzufügen</button>

                {/* Group Picker */}
                {showGroupPicker && (
                    <div style={{ marginTop: 10, ...glass, padding: 10, maxHeight: 200, overflowY: 'auto' }}>
                        {availableGroups.length === 0 && <div style={{ fontSize: 12, color: '#475569' }}>Keine weiteren Gruppen</div>}
                        {availableGroups.map(g => (
                            <button
                                key={g.id}
                                onClick={() => handleAdd(g)}
                                disabled={addingId === g.id}
                                style={{
                                    display: 'block', width: '100%', textAlign: 'left',
                                    padding: '7px 10px', borderRadius: 6, marginBottom: 4,
                                    background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)',
                                    color: '#e2e8f0', cursor: 'pointer', fontSize: 12,
                                }}
                            >{addingId === g.id ? '…' : g.displayName}</button>
                        ))}
                    </div>
                )}
            </div>

            {/* Link zu Entra Portal */}
            <div style={{ borderTop: '1px solid rgba(255,255,255,0.07)', paddingTop: 16 }}>
                <a
                    href={`https://entra.microsoft.com/#view/Microsoft_AAD_UsersAndTenants/UserProfileMenuBlade/~/overview/userId/${user.id}`}
                    target="_blank" rel="noopener noreferrer"
                    style={{
                        display: 'block', padding: '9px 14px', borderRadius: 8, fontSize: 13, textAlign: 'center',
                        background: 'rgba(99,102,241,0.12)', border: '1px solid rgba(99,102,241,0.3)',
                        color: '#a5b4fc', textDecoration: 'none',
                    }}
                >Im Entra-Portal öffnen ↗</a>
            </div>
        </div>
    );
}

// ─── Users Tab ────────────────────────────────────────────────────────────────

function UsersTab({ users, selectedUser, onUserClick }) {
    const [search, setSearch]     = useState('');
    const [filterMfa, setFilterMfa] = useState('');

    const filtered = users.filter(u => {
        const q = search.toLowerCase();
        const matchSearch = !q || u.displayName?.toLowerCase().includes(q) || u.mail?.toLowerCase().includes(q) || u.department?.toLowerCase().includes(q);
        const matchMfa = filterMfa === '' || (filterMfa === 'mfa' ? u.mfaRegistered : u.mfaRegistered === false);
        return matchSearch && matchMfa;
    });

    return (
        <div>
            <div style={{ display: 'flex', gap: 10, marginBottom: 16 }}>
                <input
                    value={search} onChange={e => setSearch(e.target.value)}
                    placeholder="Benutzer, E-Mail oder Abteilung suchen…"
                    style={{
                        flex: 1, padding: '9px 14px', borderRadius: 8, outline: 'none',
                        background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)',
                        color: '#fff', fontSize: 13,
                    }}
                />
                <select value={filterMfa} onChange={e => setFilterMfa(e.target.value)} style={{
                    padding: '9px 14px', borderRadius: 8, outline: 'none',
                    background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)',
                    color: '#fff', fontSize: 13,
                }}>
                    <option value="">Alle Benutzer</option>
                    <option value="mfa">MFA aktiv</option>
                    <option value="nomfa">Kein MFA</option>
                </select>
            </div>

            <div style={{ ...glass, overflow: 'hidden' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                    <thead>
                        <tr style={{ borderBottom: '1px solid rgba(255,255,255,0.08)' }}>
                            {['Benutzer', 'E-Mail / Stelle', 'Abteilung', 'Status', ''].map(h => (
                                <th key={h} style={{ padding: '12px 16px', textAlign: 'left', fontSize: 11, color: '#64748b', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em' }}>{h}</th>
                            ))}
                        </tr>
                    </thead>
                    <tbody>
                        {filtered.map(u => (
                            <tr
                                key={u.id}
                                onClick={() => onUserClick(u)}
                                style={{
                                    borderBottom: '1px solid rgba(255,255,255,0.05)', cursor: 'pointer',
                                    background: selectedUser?.id === u.id ? 'rgba(99,102,241,0.1)' : 'transparent',
                                    transition: 'background 0.15s',
                                }}
                                onMouseEnter={e => { if (selectedUser?.id !== u.id) e.currentTarget.style.background = 'rgba(255,255,255,0.03)'; }}
                                onMouseLeave={e => { e.currentTarget.style.background = selectedUser?.id === u.id ? 'rgba(99,102,241,0.1)' : 'transparent'; }}
                            >
                                <td style={{ padding: '11px 16px' }}>
                                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                                        <Avatar name={u.displayName} size={34} />
                                        <span style={{ fontWeight: 600, fontSize: 13, color: '#e2e8f0' }}>{u.displayName}</span>
                                    </div>
                                </td>
                                <td style={{ padding: '11px 16px' }}>
                                    <div style={{ fontSize: 12, color: '#94a3b8' }}>{u.mail}</div>
                                    {u.jobTitle && <div style={{ fontSize: 11, color: '#64748b', marginTop: 1 }}>{u.jobTitle}</div>}
                                </td>
                                <td style={{ padding: '11px 16px', fontSize: 12, color: '#64748b' }}>{u.department || '—'}</td>
                                <td style={{ padding: '11px 16px' }}>
                                    <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
                                        <span style={{
                                            padding: '2px 8px', borderRadius: 8, fontSize: 11, fontWeight: 600,
                                            background: u.accountEnabled ? 'rgba(34,197,94,0.15)' : 'rgba(239,68,68,0.15)',
                                            color: u.accountEnabled ? '#22c55e' : '#ef4444',
                                            border: `1px solid ${u.accountEnabled ? 'rgba(34,197,94,0.3)' : 'rgba(239,68,68,0.3)'}`,
                                        }}>{u.accountEnabled ? 'Aktiv' : 'Deaktiviert'}</span>
                                        {u.mfaRegistered !== null && !u.mfaRegistered && (
                                            <span style={{
                                                padding: '2px 8px', borderRadius: 8, fontSize: 11, fontWeight: 600,
                                                background: 'rgba(245,158,11,0.15)', color: '#f59e0b',
                                                border: '1px solid rgba(245,158,11,0.3)',
                                            }}>Kein MFA</span>
                                        )}
                                    </div>
                                </td>
                                <td style={{ padding: '11px 16px' }}>
                                    <button style={{
                                        padding: '5px 12px', borderRadius: 6, fontSize: 12,
                                        background: 'rgba(99,102,241,0.15)', border: '1px solid rgba(99,102,241,0.3)',
                                        color: '#a5b4fc', cursor: 'pointer',
                                    }}>Details</button>
                                </td>
                            </tr>
                        ))}
                        {filtered.length === 0 && (
                            <tr><td colSpan={5} style={{ padding: '24px 16px', textAlign: 'center', color: '#475569', fontSize: 13 }}>Keine Benutzer gefunden</td></tr>
                        )}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

// ─── Groups Tab ───────────────────────────────────────────────────────────────

function GroupsTab({ groups }) {
    const [expandedId, setExpandedId]       = useState(null);
    const [members, setMembers]             = useState({});
    const [loadingId, setLoadingId]         = useState(null);

    const toggle = async (group) => {
        if (expandedId === group.id) { setExpandedId(null); return; }
        setExpandedId(group.id);
        if (members[group.id]) return;
        setLoadingId(group.id);
        try {
            const m = await entraService.getGroupMembers(group.id);
            setMembers(prev => ({ ...prev, [group.id]: m }));
        } catch { toast.error('Mitglieder konnten nicht geladen werden'); }
        finally { setLoadingId(null); }
    };

    return (
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 14 }}>
            {groups.map(g => {
                const isOpen = expandedId === g.id;
                const gMembers = members[g.id] || [];
                return (
                    <div key={g.id} style={{ ...glass, overflow: 'hidden' }}>
                        <div
                            style={{ padding: '14px 18px', cursor: 'pointer', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}
                            onClick={() => toggle(g)}
                        >
                            <div>
                                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                    <span style={{ fontSize: 16 }}>👥</span>
                                    <span style={{ fontWeight: 700, fontSize: 14, color: '#e2e8f0' }}>{g.displayName}</span>
                                </div>
                                {g.description && <div style={{ fontSize: 11, color: '#64748b', marginTop: 3 }}>{g.description}</div>}
                            </div>
                            <span style={{ color: '#475569', fontSize: 12 }}>{isOpen ? '▲' : '▼'}</span>
                        </div>

                        {isOpen && (
                            <div style={{ borderTop: '1px solid rgba(255,255,255,0.07)', padding: '12px 18px' }}>
                                {loadingId === g.id ? (
                                    <div style={{ fontSize: 12, color: '#475569' }}>Wird geladen…</div>
                                ) : gMembers.length === 0 ? (
                                    <div style={{ fontSize: 12, color: '#475569' }}>Keine Mitglieder</div>
                                ) : (
                                    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                                        {gMembers.map(u => (
                                            <div key={u.id} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                                                <Avatar name={u.displayName} size={28} />
                                                <div>
                                                    <div style={{ fontSize: 12, color: '#e2e8f0', fontWeight: 600 }}>{u.displayName}</div>
                                                    <div style={{ fontSize: 10, color: '#64748b' }}>{u.mail || u.userPrincipalName}</div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </div>
                        )}
                    </div>
                );
            })}
        </div>
    );
}

// ─── Roles Tab ────────────────────────────────────────────────────────────────

function RolesTab({ roles }) {
    const active = roles.filter(r => r.members?.length > 0);
    const inactive = roles.filter(r => !r.members?.length);

    const RoleCard = ({ role }) => {
        const risk = getRoleRisk(role.displayName);
        const s = riskStyle[risk];
        return (
            <div style={{ ...glass, padding: '16px 20px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 8 }}>
                    <div style={{ flex: 1 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                            <span style={{ fontWeight: 700, fontSize: 14, color: '#e2e8f0' }}>{role.displayName}</span>
                            <span style={{
                                padding: '2px 8px', borderRadius: 8, fontSize: 11, fontWeight: 700,
                                background: s.bg, color: s.text, border: `1px solid ${s.border}`,
                            }}>{risk.charAt(0).toUpperCase() + risk.slice(1)}</span>
                        </div>
                        {role.description && <div style={{ fontSize: 12, color: '#64748b', marginBottom: 10 }}>{role.description}</div>}
                    </div>
                </div>
                {role.members?.length > 0 ? (
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                        {role.members.map(m => (
                            <div key={m.id} style={{
                                display: 'flex', alignItems: 'center', gap: 6,
                                padding: '4px 10px', borderRadius: 20,
                                background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.1)',
                            }}>
                                <Avatar name={m.displayName} size={20} />
                                <span style={{ fontSize: 12, color: '#e2e8f0' }}>{m.displayName}</span>
                            </div>
                        ))}
                    </div>
                ) : (
                    <span style={{ fontSize: 12, color: '#475569' }}>Keine Zuweisung</span>
                )}
            </div>
        );
    };

    return (
        <div>
            {active.length > 0 && (
                <div style={{ marginBottom: 24 }}>
                    <div style={{ fontSize: 12, color: '#64748b', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 12 }}>
                        Belegte Rollen ({active.length})
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                        {active.map(r => <RoleCard key={r.id} role={r} />)}
                    </div>
                </div>
            )}
            {inactive.length > 0 && (
                <div>
                    <div style={{ fontSize: 12, color: '#475569', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 12 }}>
                        Nicht belegt ({inactive.length})
                    </div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                        {inactive.map(r => <RoleCard key={r.id} role={r} />)}
                    </div>
                </div>
            )}
        </div>
    );
}

// ─── Hauptseite ───────────────────────────────────────────────────────────────

export default function EntraPage() {
    const { isAdmin } = useAuth();
    const [activeTab, setActiveTab] = useState('users');
    const [users, setUsers]   = useState([]);
    const [groups, setGroups] = useState([]);
    const [roles, setRoles]   = useState([]);
    const [loading, setLoading]   = useState(true);
    const [syncing, setSyncing]   = useState(false);
    const [selectedUser, setSelectedUser] = useState(null);

    const loadUsers = useCallback(async () => {
        try {
            const data = await entraService.getUsers();
            setUsers(data);
        } catch (e) {
            toast.error(`Benutzer: ${e.response?.data?.message || e.message}`);
        }
    }, []);

    const loadAll = useCallback(async () => {
        setLoading(true);
        try {
            const [u, g, r] = await Promise.allSettled([
                entraService.getUsers(),
                entraService.getGroups(),
                entraService.getRoles(),
            ]);
            if (u.status === 'fulfilled') setUsers(u.value);
            else toast.error(`Benutzer: ${u.reason?.response?.data?.message || u.reason?.message}`);

            if (g.status === 'fulfilled') setGroups(g.value);
            else toast.warn(`Gruppen: ${g.reason?.response?.data?.message || g.reason?.message}`);

            if (r.status === 'fulfilled') setRoles(r.value);
            else toast.warn(`Rollen: ${r.reason?.response?.data?.message || r.reason?.message}`);
        } finally {
            setLoading(false);
        }
    }, []);

    useEffect(() => { loadAll(); }, [loadAll]);

    const handleSync = async () => {
        setSyncing(true);
        try {
            await loadAll();
            toast.success('Daten aus Entra ID aktualisiert');
        } finally {
            setSyncing(false);
        }
    };

    const noMfa    = users.filter(u => u.mfaRegistered === false).length;
    const inactive = users.filter(u => !u.accountEnabled).length;
    const adminCount = roles.reduce((sum, r) => sum + (r.members?.length || 0), 0);

    const tabs = [
        { key: 'users',  label: 'Benutzer',     icon: '👤', count: users.length },
        { key: 'groups', label: 'Gruppen',      icon: '👥', count: groups.length },
        { key: 'roles',  label: 'Admin-Rollen', icon: '🛡️', count: roles.filter(r => r.members?.length > 0).length },
    ];

    return (
        <div style={{ padding: '28px 32px', maxWidth: 1400, margin: '0 auto', color: '#e2e8f0' }}>
            {/* Header */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 28 }}>
                <div>
                    <h1 style={{ margin: 0, fontSize: 24, fontWeight: 800, color: '#f1f5f9', marginBottom: 4 }}>
                        Entra ID Rechteverwaltung
                    </h1>
                    <p style={{ margin: 0, color: '#64748b', fontSize: 13 }}>
                        Benutzer, Gruppen und Admin-Rollen aus Microsoft Entra ID
                    </p>
                </div>
                <button
                    onClick={handleSync}
                    disabled={syncing}
                    style={{
                        padding: '9px 18px', borderRadius: 8, fontSize: 13, fontWeight: 600,
                        background: syncing ? 'rgba(255,255,255,0.04)' : 'rgba(255,255,255,0.06)',
                        border: '1px solid rgba(255,255,255,0.12)',
                        color: syncing ? '#475569' : '#94a3b8', cursor: syncing ? 'default' : 'pointer',
                    }}
                >{syncing ? '⏳ Wird geladen…' : '🔄 Aktualisieren'}</button>
            </div>

            {/* Stats */}
            {!loading && (
                <div style={{ display: 'flex', gap: 14, marginBottom: 28, flexWrap: 'wrap' }}>
                    <StatCard icon="👤" label="Benutzer gesamt"     value={users.length}   sub={inactive > 0 ? `${inactive} deaktiviert` : 'Alle aktiv'} />
                    <StatCard icon="👥" label="Gruppen"             value={groups.length}  sub="in Entra ID" />
                    <StatCard icon="🛡️" label="Admin-Rollenzuweisungen" value={adminCount} sub="Directory Roles" color={adminCount > 3 ? '#f97316' : '#e2e8f0'} />
                    <StatCard icon="⚠️" label="Ohne MFA"            value={noMfa}          sub="Handlungsbedarf" color={noMfa > 0 ? '#f59e0b' : '#22c55e'} />
                    {users.length > 0 && (
                        <StatCard icon="🔐" label="MFA-Abdeckung"
                            value={`${Math.round(((users.length - noMfa) / users.length) * 100)}%`}
                            sub="der Benutzer" color={noMfa === 0 ? '#22c55e' : '#f59e0b'} />
                    )}
                </div>
            )}

            {/* Lade-Indikator */}
            {loading && (
                <div style={{ ...glass, padding: '40px', textAlign: 'center', marginBottom: 24, color: '#64748b', fontSize: 14 }}>
                    ⏳ Daten werden aus Entra ID geladen…
                </div>
            )}

            {/* Tabs */}
            {!loading && (
                <>
                    <div style={{ display: 'flex', gap: 4, marginBottom: 20, borderBottom: '1px solid rgba(255,255,255,0.07)' }}>
                        {tabs.map(t => (
                            <button
                                key={t.key}
                                onClick={() => setActiveTab(t.key)}
                                style={{
                                    padding: '10px 20px', borderRadius: '8px 8px 0 0', fontSize: 13, fontWeight: 600,
                                    background: activeTab === t.key ? 'rgba(99,102,241,0.15)' : 'transparent',
                                    border: activeTab === t.key ? '1px solid rgba(99,102,241,0.3)' : '1px solid transparent',
                                    borderBottom: activeTab === t.key ? '1px solid rgba(10,15,30,1)' : '1px solid transparent',
                                    color: activeTab === t.key ? '#a5b4fc' : '#64748b',
                                    cursor: 'pointer', marginBottom: -1,
                                    display: 'flex', alignItems: 'center', gap: 6,
                                }}
                            >
                                {t.icon} {t.label}
                                <span style={{
                                    padding: '1px 7px', borderRadius: 10, fontSize: 11,
                                    background: activeTab === t.key ? 'rgba(99,102,241,0.3)' : 'rgba(255,255,255,0.06)',
                                    color: activeTab === t.key ? '#c7d2fe' : '#475569',
                                }}>{t.count}</span>
                            </button>
                        ))}
                    </div>

                    <div style={{ marginRight: selectedUser ? 416 : 0, transition: 'margin-right 0.2s' }}>
                        {activeTab === 'users'  && <UsersTab  users={users}   selectedUser={selectedUser} onUserClick={setSelectedUser} />}
                        {activeTab === 'groups' && <GroupsTab groups={groups} />}
                        {activeTab === 'roles'  && <RolesTab  roles={roles}   />}
                    </div>
                </>
            )}

            {/* Detail Panel */}
            <UserDetailPanel
                user={selectedUser}
                onClose={() => setSelectedUser(null)}
                onGroupRemove={loadUsers}
                onGroupAdd={loadUsers}
            />
        </div>
    );
}
