const AdministrationView = ({ currentUser, userProperties, isActiveView, pendingKbDraft, onClearPendingKbDraft }) => {
    const RoleModal = window.RoleModal;
    const ArticleModal = window.ArticleModal;
    const PropertiesManagementModal = window.PropertiesManagementModal;
    const { useState, useEffect, useRef } = React;

    const [activeTab, setActiveTab] = useState('roles');
    const [roles, setRoles] = useState([]);
    const [articles, setArticles] = useState([]);
    const [loading, setLoading] = useState(true);
    const [showRoleModal, setShowRoleModal] = useState(false);
    const [showArticleModal, setShowArticleModal] = useState(false);
    const [editingRole, setEditingRole] = useState(null);
    const [editingArticle, setEditingArticle] = useState(null);
    const [saving, setSaving] = useState(false);

    // Knowledge Base Explorer state - database-driven navigation
    const [kbItems, setKbItems] = useState([]);
    const [kbPath, setKbPath] = useState([]); // Breadcrumb path: [{id, title}, ...]
    const [kbCurrentFolderId, setKbCurrentFolderId] = useState(null);
    const [kbSearch, setKbSearch] = useState('');
    const [kbPropertyFilter, setKbPropertyFilter] = useState('');
    const [kbShowPending, setKbShowPending] = useState(false);
    const [showFolderModal, setShowFolderModal] = useState(false);
    const [newFolderName, setNewFolderName] = useState('');
    const [showHistoryModal, setShowHistoryModal] = useState(false);
    const [historyVersions, setHistoryVersions] = useState([]);
    const [historyArticleId, setHistoryArticleId] = useState(null);
    const [previewArticle, setPreviewArticle] = useState(null);
    const [returnedToMe, setReturnedToMe] = useState([]); // Rejected KB articles returned to the author
    const [openDocActionsId, setOpenDocActionsId] = useState(null); // Which document's Actions menu is open
    const [actionsDropdownPosition, setActionsDropdownPosition] = useState({ top: 0, right: 0 });
    const [kbAddChoiceOpen, setKbAddChoiceOpen] = useState(false);

    // Audit Logs state
    const [auditLogs, setAuditLogs] = useState([]);
    const [auditLogsLimit, setAuditLogsLimit] = useState(100);
    const [auditLogDetailView, setAuditLogDetailView] = useState(null); // log entry shown in details modal

    // Human-readable audit summary for table and modal (no raw JSON for normal view)
    const getAuditSummary = (detailsObj, log) => {
        if (!detailsObj || typeof detailsObj !== 'object') {
            if (log?.details && typeof log.details === 'string') return log.details.slice(0, 80) + (log.details.length > 80 ? '…' : '');
            return 'Details recorded';
        }
        const d = detailsObj;
        if (d.note && typeof d.note === 'string') {
            const note = d.note.trim();
            const n = d.affected_users;
            if (n != null && n !== '') return n === 1 ? `${note} (1 user affected).` : `${note} (${n} user(s) affected).`;
            return note;
        }
        if (d.changes && typeof d.changes === 'object') {
            const count = Object.keys(d.changes).length;
            return count === 1 ? '1 field changed' : `${count} fields changed`;
        }
        if (d.updated_values && typeof d.updated_values === 'object') {
            const keys = Object.keys(d.updated_values);
            if (keys.length === 0) return 'No values updated';
            const labels = keys.map(k => k.replace(/_/g, ' ')).join(', ');
            return keys.length === 1 ? `Updated: ${labels}` : `Updated: ${labels}`;
        }
        if (Array.isArray(d.updated) && d.updated.length) {
            const labels = d.updated.map(f => f.replace(/_/g, ' ')).join(', ');
            return d.updated.length === 1 ? `Updated: ${labels}` : `Updated: ${labels}`;
        }
        if (d.action === 'reorder') return 'Order of items was reordered';
        if (d.title != null) {
            const title = String(d.title).slice(0, 50) + (String(d.title).length > 50 ? '…' : '');
            if (d.restored_from != null) return `Article "${title}" restored from version ${d.restored_from}`;
            if (d.reason != null) return `Article "${title}" rejected: ${String(d.reason).slice(0, 60)}${String(d.reason).length > 60 ? '…' : ''}`;
            if (log?.action === 'approve') return `Article "${title}" approved`;
            if (log?.action === 'reject') return `Article "${title}" rejected`;
            if (log?.action === 'delete') return d.is_folder ? `Folder "${title}" deleted` : `Article "${title}" deleted`;
            if (log?.action === 'update') return `Article "${title}" updated`;
            if (log?.action === 'create') return d.is_folder ? `Folder "${title}" created` : `Article "${title}" created`;
            return `"${title}"`;
        }
        if (d.name != null && d.display_name != null) return log?.action === 'create' ? `Role "${d.display_name}" created` : `Role "${d.display_name}" (${d.name})`;
        if (d.name != null) return log?.action === 'create' ? `Created: "${String(d.name).slice(0, 40)}"` : `"${String(d.name).slice(0, 40)}"`;
        if (d.reason != null) return String(d.reason).slice(0, 80) + (String(d.reason).length > 80 ? '…' : '');
        if (d.status != null) return `Status: ${d.status}`;
        if (d.code != null || d.property_code != null) return d.name != null ? `"${d.name}"` : (d.code || d.property_code || '');
        return 'Details recorded';
    };

    useEffect(() => {
        loadData();
    }, [activeTab]);

    // When arriving from AI chat with a KB draft, open the article modal with the draft and clear the pending draft
    useEffect(() => {
        if (!isActiveView || !pendingKbDraft) return;
        setEditingArticle({
            title: pendingKbDraft.title || '',
            content: pendingKbDraft.content || '',
            parent_id: null,
            ...(pendingKbDraft.category && { category: pendingKbDraft.category })
        });
        setShowArticleModal(true);
        onClearPendingKbDraft?.();
    }, [isActiveView, pendingKbDraft]);

    // Administration (Roles & Permissions, Audit) is only for users with Manage Settings. KB-only users see only Knowledge Base; they must not see Roles or Audit.
    const hasManageRolesOrSettings = currentUser?.can_manage_settings === true;
    const canRoles = hasManageRolesOrSettings;
    const canKb = !!(window.canViewKnowledgeBase && window.canViewKnowledgeBase(currentUser))
        || !!(window.canManageKnowledgeBase && window.canManageKnowledgeBase(currentUser))
        || !!(window.canApproveKnowledgeBase && window.canApproveKnowledgeBase(currentUser))
        || !!(window.canSubmitKnowledgeBase && window.canSubmitKnowledgeBase(currentUser))
        || !!(window.canEditKnowledgeBase && window.canEditKnowledgeBase(currentUser));
    // Audit: only requires can_view_audit_logs (independent of Manage Settings).
    const canAudit = currentUser?.can_view_audit_logs === true;
    // KB action flags: only render buttons when user has the specific permission (do not load button at all without permission).
    const canManageKb = !!(window.canManageKnowledgeBase && window.canManageKnowledgeBase(currentUser));
    const canApproveKb = !!(window.canApproveKnowledgeBase && window.canApproveKnowledgeBase(currentUser));
    const canSubmitKb = !!(window.canSubmitKnowledgeBase && window.canSubmitKnowledgeBase(currentUser));
    const canEditKb = !!(window.canEditKnowledgeBase && window.canEditKnowledgeBase(currentUser));
    useEffect(() => {
        const allowed = [canRoles && 'roles', canKb && 'kb', canAudit && 'audit'].filter(Boolean);
        if (allowed.length && !allowed.includes(activeTab)) setActiveTab(allowed[0]);
    }, [canRoles, canKb, canAudit]);

    const hasAccessModifiers = (item) => {
        if (!item) return false;
        const arr = (v) => Array.isArray(v) && v.length > 0;
        return arr(item.applies_to_properties) || arr(item.allowed_users) || arr(item.allowed_roles) || arr(item.allowed_brands);
    };
    const getAccessModifierTooltip = (item) => {
        if (!item) return '';
        const parts = [];
        if (Array.isArray(item.applies_to_properties) && item.applies_to_properties.length)
            parts.push('Property: ' + item.applies_to_properties.join(', '));
        if (Array.isArray(item.allowed_roles) && item.allowed_roles.length)
            parts.push('Role: ' + item.allowed_roles.length + (item.allowed_roles.length === 1 ? ' role' : ' roles'));
        if (Array.isArray(item.allowed_users) && item.allowed_users.length)
            parts.push('User: ' + item.allowed_users.join(', '));
        if (Array.isArray(item.allowed_brands) && item.allowed_brands.length)
            parts.push('Brand: ' + item.allowed_brands.join(', '));
        return parts.length ? 'Access restricted to: ' + parts.join(' • ') : '';
    };

    const loadData = async () => {
        setLoading(true);
        try {
            if (activeTab === 'roles' && canRoles) {
                const res = await fetch('/api/roles', {
                    headers: window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username }
                });
                if (res.ok) {
                    const data = await res.json();
                    setRoles(data.roles || []);
                }
            } else if (activeTab === 'kb') {
                const [listRes, returnedRes] = await Promise.all([
                    fetch('/api/knowledge-base', { headers: window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username } }),
                    fetch('/api/knowledge-base/returned-to-me', { headers: window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username } })
                ]);
                if (listRes.ok) {
                    const data = await listRes.json();
                    setKbItems(data.items || []);
                    setArticles(data.items || []);
                }
                if (returnedRes.ok) {
                    const data = await returnedRes.json();
                    setReturnedToMe(data.items || []);
                } else {
                    setReturnedToMe([]);
                }
            } else if (activeTab === 'audit' && canAudit) {
                const res = await fetch(`/api/audit-logs?limit=${auditLogsLimit}`, {
                    headers: window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username }
                });
                if (res.ok) {
                    const data = await res.json();
                    setAuditLogs(data.logs || []);
                } else {
                    setAuditLogs([]);
                }
            }
        } catch (error) {
            console.error('Failed to load data:', error);
        } finally {
            setLoading(false);
        }
    };

    // Refetch when this view becomes active; keep ref updated so interval/callbacks see latest loadData
    const loadDataRef = useRef(loadData);
    loadDataRef.current = loadData;
    const hasModalOpen = showRoleModal || showArticleModal || showFolderModal || showHistoryModal || !!previewArticle;
    const hasModalOpenRef = useRef(hasModalOpen);
    hasModalOpenRef.current = hasModalOpen;

    useEffect(() => {
        if (!isActiveView || hasModalOpenRef.current) return;
        if (typeof loadDataRef.current === 'function') loadDataRef.current();
    }, [isActiveView, activeTab]);

    useEffect(() => {
        if (!isActiveView) return;
        const interval = setInterval(() => {
            if (hasModalOpenRef.current) return;
            if (typeof loadDataRef.current === 'function') loadDataRef.current();
        }, 45000);
        return () => clearInterval(interval);
    }, [isActiveView]);

    const handleSaveRole = async (roleData) => {
        setSaving(true);
        try {
            const url = editingRole ? `/api/roles/${editingRole.id}` : '/api/roles';
            const method = editingRole ? 'PUT' : 'POST';

            const res = await fetch(url, {
                method,
                headers: {
                    'Content-Type': 'application/json',
                    'X-OTO-User': currentUser.Username
                },
                body: JSON.stringify(roleData)
            });

            const data = await res.json().catch(() => ({}));
            if (res.ok) {
                setShowRoleModal(false);
                setEditingRole(null);
                loadData();
                window.otoEvents?.emit('roles-updated');
                window.otoEvents?.emit('current-user-updated');
                window.otoNotify?.toast('Role saved successfully!', 'success');
                if (data.view_all_properties_removed && data.affected_users_count) {
                    window.otoNotify?.toast(
                        `View All Properties was removed. Property access was cleared for ${data.affected_users_count} user(s) with this role. They need to be assigned to properties.`,
                        'warning',
                        { duration: 8000 }
                    );
                }
            } else {
                window.otoNotify?.toast(data.detail || 'Failed to save role', 'error');
            }
        } catch (error) {
            window.otoNotify?.toast('Error saving role', 'error');
        } finally {
            setSaving(false);
        }
    };

    const handleDeleteRole = async (roleId) => {
        const ok = await window.otoNotify?.confirm({ title: 'Delete role', message: 'Are you sure you want to delete this role?', confirmLabel: 'Delete', danger: true });
        if (!ok) return;

        try {
            const res = await fetch(`/api/roles/${roleId}`, {
                method: 'DELETE',
                headers: window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username }
            });

            if (res.ok) {
                loadData();
                window.otoEvents?.emit('roles-updated');
                window.otoNotify?.toast('Role deleted successfully!', 'success');
            } else {
                const error = await res.json();
                window.otoNotify?.toast(error.detail || 'Failed to delete role', 'error');
            }
        } catch (error) {
            window.otoNotify?.toast('Error deleting role', 'error');
        }
    };

    const handleReorderRoles = async (roleOrders) => {
        try {
            const res = await fetch('/api/roles/reorder', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    ...(window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username })
                },
                body: JSON.stringify({
                    role_orders: roleOrders
                })
            });

            if (res.ok) {
                loadData();
                window.otoEvents?.emit('roles-updated');
                window.otoNotify?.toast('Role order updated!', 'success');
            } else {
                const error = await res.json();
                window.otoNotify?.toast(error.detail || 'Failed to reorder roles', 'error');
            }
        } catch (error) {
            window.otoNotify?.toast('Error reordering roles', 'error');
        }
    };

    const handleSaveArticle = async (articleData) => {
        setSaving(true);
        try {
            const url = (editingArticle && editingArticle.id) ? `/api/knowledge-base/${editingArticle.id}` : '/api/knowledge-base';
            const method = (editingArticle && editingArticle.id) ? 'PUT' : 'POST';

            const res = await fetch(url, {
                method,
                headers: {
                    'Content-Type': 'application/json',
                    'X-OTO-User': currentUser.Username
                },
                body: JSON.stringify(articleData)
            });

            if (res.ok) {
                const result = await res.json();
                setShowArticleModal(false);
                setEditingArticle(null);
                loadData();
                window.otoNotify?.toast((editingArticle && editingArticle.id) ? 'Item updated successfully!' : 'Item created successfully!', 'success');
                return { success: true, data: result };
            } else {
                const error = await res.json();
                window.otoNotify?.toast(error.detail || 'Failed to save', 'error');
                return { success: false };
            }
        } catch (error) {
            window.otoNotify?.toast('Error saving: ' + error.message, 'error');
            return { success: false };
        } finally {
            setSaving(false);
        }
    };

    const handleDeleteArticle = async (articleId) => {
        const ok = await window.otoNotify?.confirm({ title: 'Delete article', message: 'Are you sure you want to delete this article?', confirmLabel: 'Delete', danger: true });
        if (!ok) return;

        try {
            const res = await fetch(`/api/knowledge-base/${articleId}`, {
                method: 'DELETE',
                headers: window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username }
            });

            if (res.ok) {
                loadData();
                window.otoNotify?.toast('Article deleted successfully!', 'success');
            } else {
                const error = await res.json();
                window.otoNotify?.toast(error.detail || 'Failed to delete article', 'error');
            }
        } catch (error) {
            window.otoNotify?.toast('Error deleting article', 'error');
        }
    };

    const handleApproveArticle = async (articleId) => {
        try {
            const res = await fetch(`/api/knowledge-base/${articleId}/approve`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-OTO-User': currentUser.Username
                }
            });

            if (res.ok) {
                loadData();
                window.otoNotify?.toast('Article approved successfully!', 'success');
            } else {
                const error = await res.json();
                window.otoNotify?.toast(error.detail || 'Failed to approve article', 'error');
            }
        } catch (error) {
            window.otoNotify?.toast('Error approving article: ' + error.message, 'error');
        }
    };

    const handleRejectArticle = async (articleId) => {
        const reason = await window.otoNotify?.prompt({ title: 'Reject article', message: 'Please provide a reason for rejection:', placeholder: 'Reason...', submitLabel: 'Reject' });
        if (!reason || !reason.trim()) {
            window.otoNotify?.toast('Rejection reason is required', 'error');
            return;
        }

        try {
            const res = await fetch(`/api/knowledge-base/${articleId}/reject`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-OTO-User': currentUser.Username
                },
                body: JSON.stringify({ reason: reason.trim() })
            });

            if (res.ok) {
                loadData();
                window.otoNotify?.toast('Article rejected', 'success');
            } else {
                const error = await res.json();
                window.otoNotify?.toast(error.detail || 'Failed to reject article', 'error');
            }
        } catch (error) {
            window.otoNotify?.toast('Error rejecting article: ' + error.message, 'error');
        }
    };

    const handleViewArticle = async (articleId) => {
        setOpenDocActionsId(null);
        try {
            const res = await fetch(`/api/knowledge-base/${articleId}`, {
                headers: window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username }
            });
            if (res.ok) {
                const data = await res.json();
                const article = data.article || data;
                // Ensure attachments array exists (API should include it, but ensure it's always an array)
                if (!article.attachments) {
                    article.attachments = [];
                }
                setPreviewArticle(article);
            } else {
                const err = await res.json();
                window.otoNotify?.toast(err.detail || 'Failed to load article', 'error');
            }
        } catch (e) {
            window.otoNotify?.toast('Failed to load article', 'error');
        }
    };

    const normalizeKbMetadata = (meta) => {
        if (!meta) return {};
        if (typeof meta === 'string') {
            try { return JSON.parse(meta); } catch { return {}; }
        }
        if (typeof meta === 'object') return meta;
        return {};
    };

    const getKbAudience = (article) => {
        const m = normalizeKbMetadata(article?.metadata);
        const a = (m.audience || m.group || '');
        if (String(a).toLowerCase() === 'oto') return 'Corporate';
        return a;
    };

    const getKbAttachments = (article) => {
        const m = normalizeKbMetadata(article?.metadata);
        return Array.isArray(m.attachments) ? m.attachments : [];
    };

    if (loading) {
        return (
            <div className="flex items-center justify-center h-full">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
            </div>
        );
    }

    const isKbOnly = canKb && !canRoles;

    return (
        <div className="h-full overflow-y-auto bg-surface">
            <div className="max-w-7xl mx-auto p-8">
                <div className="mb-8">
                    <h1 className="text-3xl font-bold text-primary mb-2">{isKbOnly ? 'Knowledge Base' : 'Administration'}</h1>
                    <p className="text-slate-600">{isKbOnly ? 'Browse and manage knowledge base articles' : 'Roles &amp; Permissions, Knowledge Base, and Audit Logs'}</p>
                </div>

                {/* Tabs */}
                <div className="flex space-x-4 mb-6 border-b border-slate-200">
                    {canRoles && (
                    <button
                        onClick={() => setActiveTab('roles')}
                        className={`px-4 py-2 font-medium transition-colors border-b-2 ${activeTab === 'roles'
                                ? 'border-primary text-primary'
                                : 'border-transparent text-slate-600 hover:text-slate-800'
                            }`}
                    >
                        Roles & Permissions
                    </button>
                    )}
                    {canKb && (
                    <button
                        onClick={() => setActiveTab('kb')}
                        className={`px-4 py-2 font-medium transition-colors border-b-2 ${activeTab === 'kb'
                                ? 'border-primary text-primary'
                                : 'border-transparent text-slate-600 hover:text-slate-800'
                            }`}
                    >
                        Knowledge Base
                    </button>
                    )}
                    {canAudit && (
                    <button
                        onClick={() => setActiveTab('audit')}
                        className={`px-4 py-2 font-medium transition-colors border-b-2 ${activeTab === 'audit'
                                ? 'border-primary text-primary'
                                : 'border-transparent text-slate-600 hover:text-slate-800'
                            }`}
                    >
                        Audit Logs
                    </button>
                    )}
                </div>

                {/* Roles Tab */}
                {activeTab === 'roles' && canRoles && (
                    <div>
                        <div className="flex justify-between items-center mb-6">
                            <h2 className="text-xl font-semibold text-slate-800">Roles</h2>
                            <button
                                onClick={() => {
                                    setEditingRole(null);
                                    setShowRoleModal(true);
                                }}
                                className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-hover transition shadow-sm"
                            >
                                Create Role
                            </button>
                        </div>

                        <div className="bg-white rounded-lg shadow-sm border border-slate-200 overflow-hidden">
                            <table className="w-full">
                                <thead className="bg-slate-50">
                                    <tr>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase w-20">Order</th>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase">Role</th>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase">Description</th>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Permissions</th>
                                        <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-gray-200">
                                    {roles.filter(r => r.name !== 'administrator' && r.name !== 'administrators' && r.name !== 'system').map((role, index, filteredRoles) => {
                                        const canMoveUp = index > 0;
                                        const canMoveDown = index < filteredRoles.length - 1;

                                        const buildRoleOrdersFromList = (orderedRoles) => {
                                            const total = orderedRoles.length;
                                            // Highest (top) gets highest sort_order
                                            return orderedRoles.map((r, i) => ({
                                                role_id: r.id,
                                                sort_order: (total - 1 - i) * 10,
                                            }));
                                        };

                                        const handleMoveUp = async () => {
                                            if (!canMoveUp) return;
                                            const newList = [...filteredRoles];
                                            // Swap current with previous
                                            [newList[index - 1], newList[index]] = [newList[index], newList[index - 1]];
                                            const roleOrders = buildRoleOrdersFromList(newList);
                                            await handleReorderRoles(roleOrders);
                                        };

                                        const handleMoveDown = async () => {
                                            if (!canMoveDown) return;
                                            const newList = [...filteredRoles];
                                            // Swap current with next
                                            [newList[index], newList[index + 1]] = [newList[index + 1], newList[index]];
                                            const roleOrders = buildRoleOrdersFromList(newList);
                                            await handleReorderRoles(roleOrders);
                                        };
                                        return (
                                            <tr key={role.id}>
                                                <td className="px-6 py-4">
                                                    <div className="flex flex-col gap-1">
                                                        <button
                                                            onClick={handleMoveUp}
                                                            disabled={!canMoveUp}
                                                            className={`p-1 rounded ${canMoveUp ? 'text-gray-600 hover:bg-gray-100' : 'text-gray-300 cursor-not-allowed'}`}
                                                            title="Move up (higher rank)"
                                                        >
                                                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
                                                            </svg>
                                                        </button>
                                                        <button
                                                            onClick={handleMoveDown}
                                                            disabled={!canMoveDown}
                                                            className={`p-1 rounded ${canMoveDown ? 'text-gray-600 hover:bg-gray-100' : 'text-gray-300 cursor-not-allowed'}`}
                                                            title="Move down (lower rank)"
                                                        >
                                                            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                                                            </svg>
                                                        </button>
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4">
                                                    <div className="font-medium text-gray-900">{role.display_name}</div>
                                                    <div className="text-xs text-gray-500 mt-0.5">Rank: {role.sort_order ?? 0}</div>
                                                </td>
                                                <td className="px-6 py-4 text-sm text-gray-600">{role.description || '—'}</td>
                                                <td className="px-6 py-4 text-sm">
                                                    <div className="flex flex-wrap gap-1">
                                                        {Object.entries(role || {})
                                                            .filter(([key, value]) => key.startsWith('can_') && value === true)
                                                            .map(([key]) => (
                                                                <span key={key} className="px-2 py-1 bg-primary/10 text-primary text-xs rounded">
                                                                    {key.replace('can_', '').replace(/_/g, ' ')}
                                                                </span>
                                                            ))
                                                        }
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4">
                                                    <div className="flex gap-2">
                                                        <button
                                                            onClick={() => {
                                                                setEditingRole(role);
                                                                setShowRoleModal(true);
                                                            }}
                                                            className="text-sm text-primary hover:text-primary-light"
                                                        >
                                                            Edit
                                                        </button>
                                                        <button
                                                            onClick={() => handleDeleteRole(role.id)}
                                                            className="text-red-600 hover:text-red-700 text-sm"
                                                        >
                                                            Delete
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                        );
                                    })}
                                </tbody>
                            </table>
                        </div>
                    </div>
                )}

                {/* Knowledge Base Tab — only render when user has at least one KB permission */}
                {activeTab === 'kb' && canKb && (
                    <div className="h-full flex flex-col">
                        <div className="flex items-center justify-between mb-6">
                            <div>
                                <h2 className="text-2xl font-bold text-gray-900">Knowledge Base</h2>
                                <p className="text-sm text-gray-600">Database-driven folder navigation</p>
                            </div>
                            <div className="flex items-center gap-3">
                                {canApproveKb && !kbShowPending && (
                                    <button
                                        onClick={() => setKbShowPending(true)}
                                        className="px-4 py-2 rounded-lg bg-primary/10 border-2 border-primary/30 text-primary hover:bg-primary/20 transition font-medium"
                                    >
                                        ⏰ Pending ({(articles || []).filter(a => a.status === 'pending_review').length})
                                    </button>
                                )}

                                {(kbPath.length > 0 || kbShowPending) && (
                                    <button
                                        onClick={() => {
                                            if (kbShowPending) {
                                                setKbShowPending(false);
                                            } else if (kbPath.length === 1) {
                                                setKbPath([]);
                                                setKbCurrentFolderId(null);
                                                loadData();
                                            } else {
                                                const newPath = kbPath.slice(0, -1);
                                                setKbPath(newPath);
                                                const parentId = newPath[newPath.length - 1]?.id || null;
                                                setKbCurrentFolderId(parentId);
                                            }
                                        }}
                                        className="px-4 py-2 border border-slate-300 rounded-lg text-slate-700 hover:bg-slate-50 transition"
                                    >
                                        ← Back
                                    </button>
                                )}

                                {(canManageKb || canSubmitKb) && !kbShowPending && (
                                    <>
                                        <button
                                            type="button"
                                            onClick={() => setKbAddChoiceOpen(true)}
                                            className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-hover transition shadow-sm font-medium"
                                        >
                                            + Add
                                        </button>
                                        {kbAddChoiceOpen && (
                                            <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4" onClick={() => setKbAddChoiceOpen(false)}>
                                                <div className="bg-white rounded-xl shadow-xl max-w-sm w-full p-5 border border-gray-200" onClick={(e) => e.stopPropagation()}>
                                                    <h3 className="text-lg font-semibold text-gray-900 mb-3">Add to Knowledge Base</h3>
                                                    <p className="text-sm text-gray-600 mb-4">What would you like to add?</p>
                                                    <div className="flex flex-col gap-2">
                                                        {canManageKb && (
                                                            <button
                                                                type="button"
                                                                onClick={() => {
                                                                    setKbAddChoiceOpen(false);
                                                                    setEditingArticle({ parent_id: kbCurrentFolderId, is_folder: true });
                                                                    setShowArticleModal(true);
                                                                }}
                                                                className="w-full text-left px-4 py-3 rounded-lg border border-gray-200 text-gray-800 hover:border-primary hover:bg-primary/5 transition font-medium"
                                                            >
                                                                📁 Folder
                                                            </button>
                                                        )}
                                                        {(canManageKb || canSubmitKb) && (
                                                            <button
                                                                type="button"
                                                                onClick={() => {
                                                                    setKbAddChoiceOpen(false);
                                                                    setEditingArticle({ parent_id: kbCurrentFolderId });
                                                                    setShowArticleModal(true);
                                                                }}
                                                                className="w-full text-left px-4 py-3 rounded-lg border border-gray-200 text-gray-800 hover:border-primary hover:bg-primary/5 transition font-medium"
                                                            >
                                                                📄 Document
                                                            </button>
                                                        )}
                                                    </div>
                                                    <button
                                                        type="button"
                                                        onClick={() => setKbAddChoiceOpen(false)}
                                                        className="mt-4 w-full px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 font-medium"
                                                    >
                                                        Cancel
                                                    </button>
                                                </div>
                                            </div>
                                        )}
                                    </>
                                )}
                            </div>
                        </div>

                        {kbPath.length > 0 && !kbShowPending && (
                            <div className="flex items-center gap-2 mb-4 text-sm text-gray-600">
                                <button onClick={() => { setKbPath([]); setKbCurrentFolderId(null); loadData(); }} className="px-2 py-1 rounded-lg text-primary hover:bg-primary/5 font-medium transition-colors">
                                    Home
                                </button>
                                {kbPath.map((crumb, idx) => (
                                    <React.Fragment key={crumb.id}>
                                        <span>→</span>
                                        <button
                                            onClick={() => {
                                                const newPath = kbPath.slice(0, idx + 1);
                                                setKbPath(newPath);
                                                setKbCurrentFolderId(crumb.id);
                                            }}
                                            className="px-2 py-1 rounded-lg text-primary hover:bg-primary/5 font-medium transition-colors"
                                        >
                                            {crumb.title}
                                        </button>
                                    </React.Fragment>
                                ))}
                            </div>
                        )}

                        <div className="mb-6">
                            <input
                                type="text"
                                value={kbSearch}
                                onChange={(e) => setKbSearch(e.target.value)}
                                placeholder="Search..."
                                className="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent"
                            />
                        </div>

                        {/* Rejected articles returned to the current user — only show section if user can submit/edit/manage */}
                        {!kbShowPending && (canSubmitKb || canEditKb || canManageKb) && (returnedToMe || []).length > 0 && (
                            <div className="mb-6 rounded-xl border-2 border-amber-200 bg-amber-50/80 p-4">
                                <h3 className="text-sm font-semibold text-amber-900 mb-2">Returned to you</h3>
                                <p className="text-xs text-amber-800 mb-3">These articles were rejected. You can edit and resubmit, or discard.</p>
                                <div className="space-y-3">
                                    {(returnedToMe || []).map(a => (
                                        <div key={a.id} className="bg-white rounded-lg border border-amber-200 p-3 flex flex-wrap items-start justify-between gap-2">
                                            <div className="min-w-0 flex-1">
                                                <div className="flex flex-wrap items-center gap-2">
                                                    <span className="font-medium text-gray-900">{a.title}</span>
                                                    {hasAccessModifiers(a) && (
                                                        <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium bg-primary/10 text-primary border border-primary/20" title={getAccessModifierTooltip(a)}>
                                                            <span aria-hidden>🔒</span>
                                                            <span>Access</span>
                                                        </span>
                                                    )}
                                                </div>
                                                {a.rejected_reason && <p className="text-sm text-amber-800 mt-1">Reason: {a.rejected_reason}</p>}
                                                <p className="text-xs text-gray-500 mt-1">Updated {a.updated_at ? new Date(a.updated_at).toLocaleString() : ''}</p>
                                            </div>
                                            <div className="flex flex-wrap gap-2">
                                                <button type="button" onClick={() => handleViewArticle(a.id)} className="px-3 py-1.5 text-sm bg-slate-600 text-white rounded-lg hover:bg-slate-700">View</button>
                                                {(canEditKb || canSubmitKb) && (
                                                    <button type="button" onClick={() => { setEditingArticle(a); setShowArticleModal(true); }} className="px-3 py-1.5 text-sm bg-primary text-white rounded-lg hover:bg-primary/90">Edit & resubmit</button>
                                                )}
                                                {(canManageKb || canEditKb || canSubmitKb) && (
                                                    <button type="button" onClick={() => handleDeleteArticle(a.id)} className="px-3 py-1.5 text-sm border border-red-300 text-red-700 rounded-lg hover:bg-red-50">Discard</button>
                                                )}
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}

                        <div className="flex-1 overflow-auto">
                            {(() => {
                                const StatusBadge = ({ status }) => {
                                    const cfg = {
                                        active: { bg: 'bg-primary/10', text: 'text-primary', label: 'Active' },
                                        pending_review: { bg: 'bg-primary/10', text: 'text-primary', label: 'Pending' },
                                        rejected: { bg: 'bg-red-100', text: 'text-red-800', label: 'Rejected' }
                                    };
                                    const s = cfg[status] || cfg.active;
                                    return <span className={`px-2 py-1 text-xs font-medium rounded ${s.bg} ${s.text}`}>{s.label}</span>;
                                };
                                const AccessModifierIndicator = ({ item, className = '' }) => {
                                    if (!hasAccessModifiers(item)) return null;
                                    const tip = getAccessModifierTooltip(item);
                                    return (
                                                                        <span
                                                                            className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs font-medium bg-primary/10 text-primary border border-primary/20 ${className}`}
                                                                            title={tip}
                                                                        >
                                                                            <span aria-hidden>🔒</span>
                                                                            <span>Access</span>
                                                                        </span>
                                                                    );
                                };

                                if (kbShowPending) {
                                    const pending = (articles || []).filter(a => a.status === 'pending_review' && !a.is_folder);
                                    return (
                                        <div>
                                            <h3 className="text-xl font-bold mb-6">Pending Verification ({pending.length})</h3>
                                            <p className="text-sm text-slate-600 mb-4">Review each edit: open the article to view full content, then approve or reject the change.</p>
                                            {pending.length > 0 ? (
                                                <div className="bg-white rounded-xl border border-slate-200 divide-y">
                                                    {pending.map(a => {
                                                                    const canApproveReject = canApproveKb;
                                                                    const isAuthor = (a.created_by || '').trim() === (currentUser?.Username || '').trim();
                                                                    const canRevoke = isAuthor && (canEditKb || canSubmitKb);
                                                                    return (
                                                        <div key={a.id} className="p-4">
                                                            <div className="flex gap-4">
                                                                <div className="flex-1">
                                                                    <div className="flex flex-wrap items-center gap-2 mb-2">
                                                                        <StatusBadge status={a.status} />
                                                                        <h3 className="font-semibold">{a.title}</h3>
                                                                        <AccessModifierIndicator item={a} />
                                                                    </div>
                                                                    {a.category && <p className="text-xs text-slate-500 mb-1">📍 {a.category}</p>}
                                                                    <p className="text-sm text-gray-600 mb-2">{a.content?.substring(0, 150)}...</p>
                                                                    <p className="text-xs text-slate-500">
                                                                        Created by {a.created_by} • {a.created_at ? new Date(a.created_at).toLocaleDateString() : ''}
                                                                        {(a.updated_by || a.updated_at) && (
                                                                            <> • Last edit: {a.updated_by || '—'} • {a.updated_at ? new Date(a.updated_at).toLocaleString() : ''}</>
                                                                        )}
                                                                    </p>
                                                                </div>
                                                                <div className="flex flex-col gap-2 flex-shrink-0">
                                                                    <button onClick={() => handleViewArticle(a.id)} className="px-4 py-2 bg-slate-600 text-white rounded hover:bg-slate-700">View</button>
                                                                    {canApproveReject && (
                                                                        <>
                                                                            <button onClick={() => handleApproveArticle(a.id)} className="px-4 py-2 bg-primary text-white rounded hover:bg-primary-hover">Approve</button>
                                                                            <button onClick={() => handleRejectArticle(a.id)} className="px-4 py-2 border border-red-300 text-red-700 rounded hover:bg-red-50">Reject</button>
                                                                        </>
                                                                    )}
                                                                    {canRevoke && (
                                                                        <button onClick={() => handleDeleteArticle(a.id)} className="px-4 py-2 border border-amber-400 text-amber-800 rounded hover:bg-amber-50">Revoke</button>
                                                                    )}
                                                                </div>
                                                            </div>
                                                        </div>
                                                                    );
                                                                    })}
                                                </div>
                                            ) : (
                                                <div className="text-center py-12"><p className="text-6xl mb-4">🎉</p><p className="font-medium">All caught up!</p></div>
                                            )}
                                        </div>
                                    );
                                }

                                // When searching: search ALL items globally
                                // When not searching: show only current folder items
                                const itemsToShow = kbSearch
                                    ? (kbItems || [])  // GLOBAL SEARCH - all items
                                    : (kbPath.length === 0
                                        ? (kbItems || []).filter(item => !item.parent_id)
                                        : (kbItems || []).filter(item => item.parent_id === kbCurrentFolderId));

                                const filtered = kbSearch
                                    ? itemsToShow.filter(item => {
                                        const q = kbSearch.toLowerCase();
                                        // Search title and category (path), NOT content
                                        const searchText = `${item.title} ${item.category || ''}`.toLowerCase();
                                        return searchText.includes(q);
                                    })
                                    : itemsToShow;

                                const folders = filtered.filter(item => item.is_folder);
                                const documents = filtered.filter(item => !item.is_folder);

                                return (
                                    <div>
                                        {folders.length > 0 && (
                                            <div className="mb-6">
                                                <h3 className="text-lg font-semibold text-gray-900 mb-4">Folders</h3>
                                                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                                                    {folders.map(folder => (
                                                        <div
                                                            key={folder.id}
                                                            className="relative bg-white rounded-xl border-2 border-slate-200 p-6 hover:border-primary hover:shadow-lg transition group"
                                                        >
                                                            {/* Main folder area - clickable */}
                                                            <div
                                                                onClick={() => {
                                                                    // If searching, build path from category to show correct breadcrumb
                                                                    if (kbSearch && folder.category) {
                                                                        // Category is like "Corporate/CapEx" - need to build path with IDs
                                                                        const categoryParts = folder.category.split('/');
                                                                        const newPath = [];

                                                                        // Build path by finding parent folders in kbItems
                                                                        for (let i = 0; i < categoryParts.length - 1; i++) {
                                                                            const partTitle = categoryParts[i];
                                                                            const parentFolder = (kbItems || []).find(item =>
                                                                                item.is_folder && item.title === partTitle
                                                                            );
                                                                            if (parentFolder) {
                                                                                newPath.push({ id: parentFolder.id, title: parentFolder.title });
                                                                            }
                                                                        }

                                                                        // Add current folder
                                                                        newPath.push({ id: folder.id, title: folder.title });

                                                                        setKbPath(newPath);
                                                                        setKbCurrentFolderId(folder.id);
                                                                        setKbSearch(''); // Clear search when navigating
                                                                    } else {
                                                                        // Normal navigation - append to current path
                                                                        setKbPath([...kbPath, { id: folder.id, title: folder.title }]);
                                                                        setKbCurrentFolderId(folder.id);
                                                                    }
                                                                }}
                                                                className="cursor-pointer"
                                                            >
                                                                <div className="w-12 h-12 rounded-lg bg-primary/10 flex items-center justify-center text-2xl font-bold text-primary mb-4 group-hover:bg-primary group-hover:text-white transition">
                                                                    📁
                                                                </div>
                                                                <div className="flex flex-wrap items-center gap-2 mb-1">
                                                                    <h4 className="font-bold text-gray-900">{folder.title}</h4>
                                                                    <AccessModifierIndicator item={folder} />
                                                                </div>
                                                                {kbSearch && folder.category && (
                                                                    <p className="text-xs text-primary font-semibold mb-1">📍 {folder.category}</p>
                                                                )}
                                                                <p className="text-xs text-gray-500 mb-12">{folder.content || 'Folder'}</p>
                                                            </div>

                                                            {/* Action buttons — only render when user has permission (button not in DOM otherwise) */}
                                                            <div className="absolute bottom-3 right-3 flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                                                                {canManageKb && (
                                                                    <button
                                                                        onClick={(e) => {
                                                                            e.stopPropagation();
                                                                            setEditingArticle(folder);
                                                                            setShowArticleModal(true);
                                                                        }}
                                                                        className="px-3 py-2 bg-primary text-white text-sm font-bold rounded-lg hover:bg-primary-hover shadow-lg"
                                                                    >
                                                                        ✏️ Edit
                                                                    </button>
                                                                )}
                                                                {canManageKb && (
                                                                    <button
                                                                        onClick={(e) => {
                                                                            e.stopPropagation();
                                                                            window.otoNotify?.confirm({ title: 'Delete folder', message: `Delete "${folder.title}"? This cannot be undone.`, confirmLabel: 'Delete', danger: true }).then(ok => { if (ok) handleDeleteArticle(folder.id); });
                                                                        }}
                                                                        className="px-3 py-2 border-2 border-red-300 text-red-700 text-sm font-bold rounded-lg hover:bg-red-50 shadow-lg transition"
                                                                    >
                                                                        🗑️ Delete
                                                                    </button>
                                                                )}
                                                            </div>
                                                        </div>
                                                    ))}
                                                </div>
                                            </div>
                                        )}

                                        {documents.length > 0 && (
                                            <div>
                                                <h3 className="text-lg font-semibold text-gray-900 mb-4">Documents</h3>
                                                <div className="bg-white rounded-xl border border-slate-200 divide-y">
                                                    {documents.map(doc => {
                                                        const isAuthor = (doc.created_by || '').trim() === (currentUser?.Username || '').trim();
                                                        const canEditDoc = canEditKb || canManageKb || (isAuthor && (doc.status === 'pending_review' || doc.status === 'rejected'));
                                                        const canDeleteDoc = canManageKb || (isAuthor && (doc.status === 'pending_review' || doc.status === 'rejected') && (canEditKb || canSubmitKb));
                                                        const canApproveReject = canApproveKb && doc.status === 'pending_review';
                                                        const showActions = true; // Always show Actions so View is available
                                                        return (
                                                        <div key={doc.id} className="p-4 hover:bg-slate-50 flex gap-4 items-start">
                                                            <div className="flex-1 min-w-0">
                                                                <div className="flex flex-wrap items-center gap-2 mb-2">
                                                                    <StatusBadge status={doc.status} />
                                                                    <h4 className="font-semibold text-gray-900">{doc.title}</h4>
                                                                    <AccessModifierIndicator item={doc} />
                                                                </div>
                                                                {kbSearch && doc.category && (
                                                                    <p className="text-xs text-primary font-semibold mb-2">📍 {doc.category}</p>
                                                                )}
                                                                <p className="text-sm text-gray-600 mb-2">{doc.content?.substring(0, 150)}...</p>
                                                                <p className="text-xs text-gray-500">By {doc.created_by} • {new Date(doc.created_at).toLocaleDateString()}</p>
                                                            </div>
                                                            {showActions && (
                                                                <div className="relative flex-shrink-0">
                                                                    <button
                                                                        type="button"
                                                                        onClick={(e) => {
                                                                            if (openDocActionsId === doc.id) {
                                                                                setOpenDocActionsId(null);
                                                                            } else {
                                                                                const rect = e.currentTarget.getBoundingClientRect();
                                                                                const viewportHeight = window.innerHeight;
                                                                                const dropdownHeight = 300; // Approximate max height
                                                                                const spaceBelow = viewportHeight - rect.bottom;
                                                                                const spaceAbove = rect.top;
                                                                                
                                                                                // Position below by default, above if not enough space below
                                                                                if (spaceBelow < dropdownHeight && spaceAbove > spaceBelow) {
                                                                                    setActionsDropdownPosition({ 
                                                                                        top: rect.top - Math.min(dropdownHeight, spaceAbove - 10), 
                                                                                        right: window.innerWidth - rect.right 
                                                                                    });
                                                                                } else {
                                                                                    setActionsDropdownPosition({ 
                                                                                        top: rect.bottom + 4, 
                                                                                        right: window.innerWidth - rect.right 
                                                                                    });
                                                                                }
                                                                                setOpenDocActionsId(doc.id);
                                                                            }
                                                                        }}
                                                                        className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-hover text-sm font-semibold shadow-sm transition flex items-center gap-1.5"
                                                                    >
                                                                        Actions
                                                                        <svg className={`w-4 h-4 transition-transform ${openDocActionsId === doc.id ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                                                                        </svg>
                                                                    </button>
                                                                    {openDocActionsId === doc.id && (
                                                                        <>
                                                                            <div className="fixed inset-0 z-10" onClick={() => setOpenDocActionsId(null)} aria-hidden="true" />
                                                                            <div 
                                                                                className="fixed py-1 bg-white border border-slate-200 rounded-lg shadow-xl z-20 min-w-[160px] max-h-[300px] overflow-y-auto"
                                                                                style={{ 
                                                                                    top: `${actionsDropdownPosition.top}px`, 
                                                                                    right: `${actionsDropdownPosition.right}px`
                                                                                }}
                                                                            >
                                                                                <button type="button" onClick={() => handleViewArticle(doc.id)} className="w-full text-left px-3 py-2 text-sm text-slate-700 hover:bg-slate-50">View</button>
                                                                                {canApproveReject && (
                                                                                    <>
                                                                                        <button type="button" onClick={() => { setOpenDocActionsId(null); handleApproveArticle(doc.id); }} className="w-full text-left px-3 py-2 text-sm text-primary hover:bg-primary/10">Approve</button>
                                                                                        <button type="button" onClick={() => { setOpenDocActionsId(null); handleRejectArticle(doc.id); }} className="w-full text-left px-3 py-2 text-sm text-red-700 hover:bg-red-50">Reject</button>
                                                                                    </>
                                                                                )}
                                                                                <HistoryVersionsButton
                                                                                    doc={doc}
                                                                                    currentUser={currentUser}
                                                                                    variant="menu"
                                                                                    onOpenModal={(articleId, versions, article) => {
                                                                                        setOpenDocActionsId(null);
                                                                                        setHistoryVersions(versions);
                                                                                        setHistoryArticleId(articleId);
                                                                                        setEditingArticle(article);
                                                                                        setShowHistoryModal(true);
                                                                                    }}
                                                                                />
                                                                                {canEditDoc && (
                                                                                    <button type="button" onClick={() => { setOpenDocActionsId(null); setEditingArticle(doc); setShowArticleModal(true); }} className="w-full text-left px-3 py-2 text-sm text-slate-700 hover:bg-slate-50">Edit</button>
                                                                                )}
                                                                                {canDeleteDoc && (
                                                                                    <button type="button" onClick={() => { setOpenDocActionsId(null); handleDeleteArticle(doc.id); }} className="w-full text-left px-3 py-2 text-sm text-red-700 hover:bg-red-50">Delete</button>
                                                                                )}
                                                                            </div>
                                                                        </>
                                                                    )}
                                                                </div>
                                                            )}
                                                        </div>
                                                        );
                                                    })}
                                                </div>
                                            </div>
                                        )}

                                        {folders.length === 0 && documents.length === 0 && (
                                            <div className="bg-white rounded-xl border border-slate-200 p-12 text-center">
                                                <p className="text-6xl mb-4">📂</p>
                                                <p className="font-medium text-gray-900 mb-2">This folder is empty</p>
                                                <p className="text-sm text-gray-500">Add folders or documents to get started</p>
                                            </div>
                                        )}
                                    </div>
                                );
                            })()}
                        </div>

                    </div>
                )}

            </div>

            {/* Role Modal */}
            {showRoleModal && (
                <RoleModal
                    role={editingRole}
                    onSave={handleSaveRole}
                    onClose={() => {
                        setShowRoleModal(false);
                        setEditingRole(null);
                    }}
                    saving={saving}
                />
            )}

            {/* Article Modal */}
            {showArticleModal && (
                <ArticleModal
                    article={editingArticle}
                    onSave={handleSaveArticle}
                    onClose={() => {
                        setShowArticleModal(false);
                        setEditingArticle(null);
                    }}
                    saving={saving}
                    currentUser={currentUser}
                    userProperties={userProperties}
                    kbPath={kbPath}
                    onOpenHistory={(articleId, versions) => {
                        setHistoryArticleId(articleId);
                        setHistoryVersions(versions || []);
                        setShowHistoryModal(true);
                    }}
                />
            )}

            {/* Version History Modal */}
            {showHistoryModal && historyArticleId && (
                <KBComponents.VersionHistoryPanel
                    isOpen={showHistoryModal}
                    onClose={() => {
                        setShowHistoryModal(false);
                        setHistoryArticleId(null);
                        setHistoryVersions([]);
                    }}
                    versions={historyVersions || []}
                    historyVersions={historyVersions || []}
                    article={editingArticle}
                    versioningMode={editingArticle?.versioning_mode || 'history'}
                    currentVersionId={historyArticleId}
                    onRestore={async (historyId) => {
                        try {
                            if (!historyArticleId) throw new Error("Missing article id");

                            const res = await fetch(`/api/knowledge-base/${historyArticleId}/restore`, {
                                method: "POST",
                                headers: {
                                    "Content-Type": "application/json",
                                    "X-OTO-User": localStorage.getItem('oto_username') || currentUser.Username
                                },
                                body: JSON.stringify({ history_id: historyId }),
                            });

                            if (!res.ok) {
                                const err = await res.json().catch(() => ({}));
                                throw new Error(err.detail || "Restore failed");
                            }

                            window.otoNotify?.toast('Version restored successfully!', 'success');
                            setShowHistoryModal(false);
                            setHistoryArticleId(null);
                            setHistoryVersions([]);

                            // Reload the data
                            if (typeof loadData === 'function') {
                                await loadData();
                            }
                        } catch (e) {
                            console.error('Restore error:', e);
                            window.otoNotify?.toast(e.message || 'Restore failed', 'error');
                        }
                    }}
                />
            )}

            {/* Document preview modal: full article info + content */}
            {previewArticle && (() => {
                const MarkdownText = window.MarkdownText;
                const statusLabel = { active: 'Active', pending_review: 'Pending review', rejected: 'Rejected' }[previewArticle.status] || previewArticle.status;
                const statusColors = { active: 'bg-primary/10 text-primary', pending_review: 'bg-primary/10 text-primary', rejected: 'bg-red-100 text-red-800' };
                const tags = Array.isArray(previewArticle.tags) ? previewArticle.tags : [];
                const attachments = previewArticle.attachments || [];
                const formatFileSize = (bytes) => {
                    if (!bytes) return '';
                    if (bytes < 1024) return bytes + ' B';
                    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
                    return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
                };
                return (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4" onClick={() => setPreviewArticle(null)}>
                    <div className="bg-white rounded-xl shadow-2xl max-w-4xl w-full max-h-[90vh] flex flex-col border border-gray-200" onClick={e => e.stopPropagation()}>
                        {/* Header */}
                        <div className="px-6 py-4 border-b border-gray-200 bg-gradient-to-r from-slate-50 to-white flex items-start justify-between flex-shrink-0">
                            <div className="flex-1 min-w-0">
                                <h3 className="text-xl font-bold text-gray-900 mb-1">{previewArticle.title}</h3>
                                <div className="flex items-center gap-3 flex-wrap">
                                    <span className={`px-2 py-1 rounded-md text-xs font-semibold border ${statusColors[previewArticle.status] || 'bg-primary/10 text-primary border-primary/20'}`}>
                                        {statusLabel}
                                    </span>
                                    <span className="text-sm text-gray-600">
                                        By <span className="font-medium">{previewArticle.author_name || previewArticle.created_by}</span>
                                    </span>
                                    {previewArticle.created_at && (
                                        <span className="text-sm text-gray-500">
                                            {new Date(previewArticle.created_at).toLocaleString()}
                                        </span>
                                    )}
                                </div>
                            </div>
                            <button 
                                type="button" 
                                onClick={() => setPreviewArticle(null)} 
                                className="ml-4 p-2 text-gray-400 hover:text-gray-600 hover:bg-gray-100 rounded-lg transition"
                                aria-label="Close"
                            >
                                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>

                        {/* Content */}
                        <div className="flex-1 overflow-y-auto px-6 py-5 min-h-0">
                            {/* Metadata Section */}
                            <div className="bg-gray-50 rounded-lg p-4 mb-6 border border-gray-200">
                                <div className="grid grid-cols-2 md:grid-cols-3 gap-4 text-sm">
                                    {previewArticle.category && (
                                        <div>
                                            <div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Category</div>
                                            <div className="text-gray-900 font-medium">{previewArticle.category}</div>
                                        </div>
                                    )}
                                    {(previewArticle.property_name || previewArticle.property_code) && (
                                        <div>
                                            <div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Property</div>
                                            <div className="text-gray-900 font-medium">{previewArticle.property_name || previewArticle.property_code}</div>
                                        </div>
                                    )}
                                    {previewArticle.visibility && (
                                        <div>
                                            <div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Visibility</div>
                                            <div className="text-gray-900 font-medium capitalize">{previewArticle.visibility}</div>
                                        </div>
                                    )}
                                    {previewArticle.updated_by && (
                                        <div>
                                            <div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Last Updated</div>
                                            <div className="text-gray-900 font-medium">{previewArticle.updated_by}</div>
                                            {previewArticle.updated_at && (
                                                <div className="text-xs text-gray-600 mt-0.5">{new Date(previewArticle.updated_at).toLocaleString()}</div>
                                            )}
                                        </div>
                                    )}
                                    {previewArticle.status === 'active' && previewArticle.approved_by && (
                                        <div>
                                            <div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Approved By</div>
                                            <div className="text-gray-900 font-medium">{previewArticle.approved_by}</div>
                                            {previewArticle.approved_at && (
                                                <div className="text-xs text-gray-600 mt-0.5">{new Date(previewArticle.approved_at).toLocaleString()}</div>
                                            )}
                                        </div>
                                    )}
                                </div>
                                {previewArticle.status === 'rejected' && previewArticle.rejected_reason && (
                                    <div className="mt-4 pt-4 border-t border-gray-300">
                                        <div className="text-xs font-semibold text-amber-700 uppercase tracking-wide mb-2">Rejection Reason</div>
                                        <div className="text-sm text-amber-900 bg-amber-50 border border-amber-200 rounded-lg p-3">{previewArticle.rejected_reason}</div>
                                    </div>
                                )}
                            </div>

                            {/* Tags */}
                            {tags.length > 0 && (
                                <div className="mb-6">
                                    <div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-2">Tags</div>
                                    <div className="flex flex-wrap gap-2">
                                        {tags.map(t => (
                                            <span key={t} className="oto-tag px-3 py-1 bg-primary/10 text-primary rounded-lg text-sm font-medium border border-primary/20">
                                                {t}
                                            </span>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {/* Attachments */}
                            {attachments.length > 0 && (
                                <div className="mb-6">
                                    <div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3">Attachments ({attachments.length})</div>
                                    <div className="space-y-2">
                                        {attachments.map(a => (
                                            <a
                                                key={a.id}
                                                href={`/api/knowledge-base/${previewArticle.id}/attachments/${a.id}/download`}
                                                target="_blank"
                                                rel="noopener noreferrer"
                                                className="flex items-center gap-3 p-3 bg-white border border-gray-200 rounded-lg hover:border-primary hover:bg-primary/5 transition group"
                                            >
                                                <div className="flex-shrink-0 w-10 h-10 bg-primary/10 rounded-lg flex items-center justify-center group-hover:bg-primary/20 transition">
                                                    <svg className="w-5 h-5 text-primary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
                                                    </svg>
                                                </div>
                                                <div className="flex-1 min-w-0">
                                                    <div className="text-sm font-medium text-gray-900 truncate group-hover:text-primary transition">
                                                        {a.original_filename || a.filename || 'Attachment'}
                                                    </div>
                                                    {a.file_size && (
                                                        <div className="text-xs text-gray-500 mt-0.5">{formatFileSize(a.file_size)}</div>
                                                    )}
                                                </div>
                                                <svg className="w-5 h-5 text-gray-400 group-hover:text-primary transition flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                                                </svg>
                                            </a>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {/* Content */}
                            <div>
                                <div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-3">Content</div>
                                <div className="prose prose-sm max-w-none text-gray-800 bg-white border border-gray-200 rounded-lg p-5">
                                    {MarkdownText ? (
                                        <MarkdownText content={previewArticle.content || ''} />
                                    ) : (
                                        <div className="whitespace-pre-wrap text-gray-700 leading-relaxed">{previewArticle.content || <span className="text-gray-400 italic">(No content)</span>}</div>
                                    )}
                                </div>
                            </div>
                        </div>

                        {/* Footer */}
                        <div className="px-6 py-4 border-t border-gray-200 bg-gray-50 flex gap-3 justify-end flex-shrink-0">
                            <button 
                                type="button" 
                                onClick={() => setPreviewArticle(null)} 
                                className="px-5 py-2.5 text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 font-medium transition shadow-sm"
                            >
                                Close
                            </button>
                            {(currentUser.can_approve_knowledge_base || currentUser.can_manage_knowledge_base) && previewArticle.status === 'pending_review' && (
                                <>
                                    <button 
                                        type="button" 
                                        onClick={async () => { await handleApproveArticle(previewArticle.id); setPreviewArticle(null); }} 
                                        className="px-5 py-2.5 bg-primary text-white rounded-lg hover:bg-primary-hover font-medium transition shadow-sm"
                                    >
                                        Approve
                                    </button>
                                    <button 
                                        type="button" 
                                        onClick={async () => { await handleRejectArticle(previewArticle.id); setPreviewArticle(null); }} 
                                        className="px-5 py-2.5 border-2 border-red-300 text-red-700 rounded-lg hover:bg-red-50 font-medium transition shadow-sm"
                                    >
                                        Reject
                                    </button>
                                </>
                            )}
                        </div>
                    </div>
                </div>
                );
            })()}

                {/* Audit Logs Tab */}
                {activeTab === 'audit' && canAudit && (
                    <div className="max-w-4xl mx-auto">
                        <div className="flex justify-between items-center mb-4">
                            <div>
                                <h2 className="text-lg font-semibold text-slate-800">Audit Logs</h2>
                                <p className="text-xs text-gray-500 mt-0.5">System activity and change tracking</p>
                            </div>
                            <div className="flex items-center gap-2">
                                <label className="text-xs text-gray-600 flex items-center gap-1.5">
                                    Limit:
                                    <select
                                        value={auditLogsLimit}
                                        onChange={(e) => {
                                            setAuditLogsLimit(parseInt(e.target.value));
                                            loadData();
                                        }}
                                        className="px-2 py-1 border border-gray-300 rounded text-xs focus:ring-2 focus:ring-primary focus:border-transparent"
                                    >
                                        <option value={50}>50</option>
                                        <option value={100}>100</option>
                                        <option value={250}>250</option>
                                        <option value={500}>500</option>
                                    </select>
                                </label>
                                <button
                                    onClick={loadData}
                                    className="px-3 py-1.5 bg-primary text-white rounded-lg hover:bg-primary-hover transition font-medium text-xs"
                                >
                                    Refresh
                                </button>
                            </div>
                        </div>

                        <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                            {auditLogs.length === 0 ? (
                                <div className="p-8 text-center text-gray-500">
                                    <p className="text-sm font-medium">No audit logs found</p>
                                    <p className="text-xs mt-1">Logs will appear here as system activity occurs.</p>
                                </div>
                            ) : (
                                <div className="overflow-x-auto max-h-[60vh] overflow-y-auto">
                                    <table className="w-full text-xs">
                                        <thead className="bg-gray-50 border-b border-gray-200">
                                            <tr>
                                                <th className="px-4 py-2 text-left font-semibold text-gray-600 uppercase tracking-wider">Timestamp</th>
                                                <th className="px-4 py-2 text-left font-semibold text-gray-600 uppercase tracking-wider">User</th>
                                                <th className="px-4 py-2 text-left font-semibold text-gray-600 uppercase tracking-wider">Action</th>
                                                <th className="px-4 py-2 text-left font-semibold text-gray-600 uppercase tracking-wider">Entity</th>
                                                <th className="px-4 py-2 text-left font-semibold text-gray-600 uppercase tracking-wider">Details</th>
                                            </tr>
                                        </thead>
                                        <tbody className="bg-white divide-y divide-gray-100">
                                            {auditLogs.map((log) => {
                                                const timestamp = log.timestamp ? new Date(log.timestamp).toLocaleString() : 'N/A';
                                                const detailsObj = typeof log.details === 'string' ? (() => { try { return JSON.parse(log.details); } catch { return null; } })() : log.details;
                                                const summary = getAuditSummary(detailsObj, log);
                                                return (
                                                    <tr key={log.id} className="hover:bg-gray-50/80 transition">
                                                        <td className="px-4 py-2.5 whitespace-nowrap text-gray-800 font-mono">
                                                            {timestamp}
                                                        </td>
                                                        <td className="px-4 py-2.5 whitespace-nowrap text-gray-800">
                                                            {log.username || 'N/A'}
                                                        </td>
                                                        <td className="px-4 py-2.5 whitespace-nowrap">
                                                            <span className="oto-tag px-1.5 py-0.5 text-xs font-medium rounded bg-primary/10 text-primary border border-primary/20">
                                                                {log.action || 'N/A'}
                                                            </span>
                                                        </td>
                                                        <td className="px-4 py-2.5 whitespace-nowrap text-gray-600">
                                                            {log.entity_type ? (
                                                                <span>
                                                                    {log.entity_display_name
                                                                        ? (log.entity_type === 'role' || log.entity_type === 'roles'
                                                                            ? `Role: ${log.entity_display_name}`
                                                                            : `${log.entity_type}: ${log.entity_display_name}${log.entity_id ? ` (#${log.entity_id})` : ''}`)
                                                                        : `${log.entity_type}${log.entity_id ? ` #${log.entity_id}` : ''}`}
                                                                </span>
                                                            ) : (
                                                                <span className="text-gray-400">—</span>
                                                            )}
                                                        </td>
                                                        <td className="px-4 py-2.5 text-gray-600 max-w-xs">
                                                            <div className="flex items-center gap-1.5 flex-wrap">
                                                                <span className="text-gray-700">{summary || <span className="text-gray-400">—</span>}</span>
                                                                <button
                                                                    type="button"
                                                                    onClick={() => setAuditLogDetailView(log)}
                                                                    className="text-primary hover:underline font-medium shrink-0"
                                                                >
                                                                    View full details
                                                                </button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                );
                                            })}
                                        </tbody>
                                    </table>
                                </div>
                            )}
                        </div>

                        {/* Audit log full-details modal */}
                        {auditLogDetailView && (
                            <div
                                className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4"
                                onClick={() => setAuditLogDetailView(null)}
                            >
                                <div
                                    className="bg-white rounded-xl shadow-xl max-w-2xl w-full max-h-[85vh] flex flex-col"
                                    onClick={(e) => e.stopPropagation()}
                                >
                                    <div className="px-6 py-4 border-b border-gray-200 flex items-center justify-between">
                                        <h3 className="text-lg font-semibold text-gray-900">Audit log details</h3>
                                        <button
                                            type="button"
                                            onClick={() => setAuditLogDetailView(null)}
                                            className="p-2 text-gray-500 hover:text-gray-700 rounded-lg hover:bg-gray-100"
                                            aria-label="Close"
                                        >
                                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" /></svg>
                                        </button>
                                    </div>
                                    <div className="px-6 py-4 overflow-y-auto flex-1 space-y-4">
                                        <dl className="grid grid-cols-2 gap-2 text-sm">
                                            <dt className="text-gray-500">Timestamp</dt>
                                            <dd className="font-mono">{auditLogDetailView.timestamp ? new Date(auditLogDetailView.timestamp).toLocaleString() : 'N/A'}</dd>
                                            <dt className="text-gray-500">User</dt>
                                            <dd>{auditLogDetailView.username || 'N/A'}</dd>
                                            <dt className="text-gray-500">Action</dt>
                                            <dd><span className="oto-tag px-2 py-0.5 rounded-full bg-primary/10 text-primary border border-primary/20 text-xs font-medium">{auditLogDetailView.action || 'N/A'}</span></dd>
                                            <dt className="text-gray-500">Entity</dt>
                                            <dd>
                                                {auditLogDetailView.entity_display_name
                                                    ? (auditLogDetailView.entity_type === 'role' || auditLogDetailView.entity_type === 'roles'
                                                        ? `Role: ${auditLogDetailView.entity_display_name}`
                                                        : `${auditLogDetailView.entity_type}: ${auditLogDetailView.entity_display_name}${auditLogDetailView.entity_id ? ` (#${auditLogDetailView.entity_id})` : ''}`)
                                                    : `${auditLogDetailView.entity_type || ''}${auditLogDetailView.entity_id ? ` #${auditLogDetailView.entity_id}` : ''}` || '—'}
                                            </dd>
                                        </dl>
                                        {(() => {
                                            const d = typeof auditLogDetailView.details === 'string' ? (() => { try { return JSON.parse(auditLogDetailView.details); } catch { return null; } })() : auditLogDetailView.details;
                                            const RawJsonCollapsible = () => (
                                                <details className="mt-3">
                                                    <summary className="text-sm font-medium text-gray-500 cursor-pointer hover:text-gray-700">Technical details (raw data)</summary>
                                                    <pre className="mt-2 text-xs text-gray-500 bg-gray-100 p-3 rounded-lg overflow-x-auto whitespace-pre-wrap break-words max-h-48 overflow-y-auto">{typeof auditLogDetailView.details === 'string' ? auditLogDetailView.details : JSON.stringify(d, null, 2)}</pre>
                                                </details>
                                            );
                                            if (!d || typeof d !== 'object') {
                                                return (
                                                    <div className="space-y-3">
                                                        <h4 className="text-sm font-semibold text-gray-700">What happened</h4>
                                                        <p className="text-sm text-gray-700">{auditLogDetailView.details && typeof auditLogDetailView.details === 'string' ? auditLogDetailView.details : '—'}</p>
                                                        {auditLogDetailView.details && <RawJsonCollapsible />}
                                                    </div>
                                                );
                                            }
                                            if (d.changes && typeof d.changes === 'object') {
                                                const normalizeForCompare = (val) => {
                                                    if (val === undefined || val === null) return '—';
                                                    if (Array.isArray(val)) return [...val].sort().join(',');
                                                    return String(val).trim();
                                                };
                                                const entries = Object.entries(d.changes).filter(([field, v]) => {
                                                    const isObj = v && typeof v === 'object' && !Array.isArray(v) && ('old' in v || 'new' in v);
                                                    if (!isObj) return true;
                                                    return normalizeForCompare(v.old) !== normalizeForCompare(v.new);
                                                });
                                                return (
                                                    <div className="space-y-3">
                                                        <h4 className="text-sm font-semibold text-gray-700">What changed</h4>
                                                        {entries.length === 0 ? (
                                                            <p className="text-sm text-gray-600">No field values changed (e.g. only reorder or no-op save).</p>
                                                        ) : (
                                                            <ul className="space-y-2 text-sm">
                                                                {entries.map(([field, v]) => {
                                                                    const isObj = v && typeof v === 'object' && !Array.isArray(v) && ('old' in v || 'new' in v);
                                                                    const oldVal = isObj ? (v.old === undefined || v.old === null ? '—' : v.old === 'All properties' ? 'All properties' : Array.isArray(v.old) ? v.old.join(', ') : String(v.old)) : null;
                                                                    const newVal = isObj ? (v.new === undefined || v.new === null ? '—' : v.new === 'All properties' ? 'All properties' : Array.isArray(v.new) ? v.new.join(', ') : String(v.new)) : String(v);
                                                                    return (
                                                                        <li key={field} className="flex flex-wrap gap-2 items-baseline bg-gray-50 rounded-lg px-3 py-2">
                                                                            <span className="font-medium text-gray-800 capitalize">{field.replace(/_/g, ' ')}:</span>
                                                                            {isObj ? (
                                                                                <span className="text-gray-700">{oldVal} → {newVal}</span>
                                                                            ) : (
                                                                                <span className="text-gray-600">{newVal}</span>
                                                                            )}
                                                                        </li>
                                                                    );
                                                                })}
                                                            </ul>
                                                        )}
                                                        <RawJsonCollapsible />
                                                    </div>
                                                );
                                            }
                                            if (d.updated_values && typeof d.updated_values === 'object') {
                                                return (
                                                    <div className="space-y-3">
                                                        <h4 className="text-sm font-semibold text-gray-700">What changed</h4>
                                                        <p className="text-sm text-gray-600 mb-2">The following values were updated:</p>
                                                        <ul className="space-y-1.5 text-sm">
                                                            {Object.entries(d.updated_values).map(([k, v]) => (
                                                                <li key={k} className="flex gap-2"><span className="font-medium text-gray-700 capitalize">{k.replace(/_/g, ' ')}:</span><span className="text-gray-600">{Array.isArray(v) ? v.join(', ') : String(v ?? '—')}</span></li>
                                                            ))}
                                                        </ul>
                                                        <RawJsonCollapsible />
                                                    </div>
                                                );
                                            }
                                            // Human-readable summary for all other shapes (note, title, name, action, etc.)
                                            const summary = getAuditSummary(d, auditLogDetailView);
                                            return (
                                                <div className="space-y-3">
                                                    <h4 className="text-sm font-semibold text-gray-700">What happened</h4>
                                                    <p className="text-sm text-gray-700 leading-relaxed">{summary}</p>
                                                    <RawJsonCollapsible />
                                                </div>
                                            );
                                        })()}
                                    </div>
                                    <div className="px-6 py-3 border-t border-gray-200 flex justify-end">
                                        <button
                                            type="button"
                                            onClick={() => setAuditLogDetailView(null)}
                                            className="px-4 py-2 bg-gray-100 text-gray-800 rounded-lg hover:bg-gray-200 font-medium text-sm"
                                        >
                                            Close
                                        </button>
                                    </div>
                                </div>
                            </div>
                        )}
                    </div>
                )}

        </div>
    );
};


if (typeof window !== 'undefined') window.AdministrationView = AdministrationView;