const ArticleModal = ({ article, onSave, onClose, saving, currentUser, userProperties = [], kbPath = [], onOpenHistory }) => {
    const { useState, useEffect, useRef } = React;
    // Determine if we're creating or editing
    const isEditing = article && article.id;
    const isCreatingInFolder = article && article.parent_id && !article.id;

    // Build the location breadcrumb
    const locationPath = isCreatingInFolder
        ? kbPath.map(p => p.title).join(' → ')
        : (isEditing && article.category ? article.category : 'Root');

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

    const initialMeta = normalizeMetadata(article?.metadata);

    const [formData, setFormData] = useState({
        title: article?.title || '',
        content: article?.content || '',
        parent_id: article?.parent_id || null,
        is_folder: article?.is_folder || false,
        applies_to_properties: article?.applies_to_properties || [],
        allowed_users: article?.allowed_users || [],
        allowed_roles: article?.allowed_roles || [],
        allowed_brands: article?.allowed_brands || [],
        tags: article?.tags || [],
        versioning_mode: article?.versioning_mode || 'history',
        audience: (String(initialMeta.audience || '').toLowerCase() === 'oto' ? 'Corporate' : (initialMeta.audience || '')),
        department: initialMeta.department || ''
    });

    // File upload state
    const [selectedFiles, setSelectedFiles] = useState([]);
    const [existingAttachments, setExistingAttachments] = useState([]);
    const [allUsers, setAllUsers] = useState([]);
    const [allRoles, setAllRoles] = useState([]);
    const [allBrands, setAllBrands] = useState([]);
    const [ancestorPerms, setAncestorPerms] = useState(null);
    const [activeTab, setActiveTab] = useState('content');
    const [propertySearch, setPropertySearch] = useState('');
    const [userSearch, setUserSearch] = useState('');
    const [roleSearch, setRoleSearch] = useState('');

    // Build tabs array — only 2 tabs: Content + Access (admin only)
    const tabs = [
        { id: 'content', label: 'Content' },
        ...(currentUser.can_manage_knowledge_base ? [{ id: 'access', label: 'Access' }] : [])
    ];

    const AUDIENCE_OPTIONS = [
        { value: '', label: '— Not set —' },
        { value: 'Hotel', label: 'Hotel (Property Ops)' },
        { value: 'Corporate', label: 'Corporate' },
        { value: 'Restaurant', label: 'Restaurant / F&B' },
        { value: 'Facilities', label: 'Facilities' },
        { value: 'Policies', label: 'Policies' },
        { value: 'Services', label: 'Services' },
        { value: 'Other', label: 'Other' }
    ];

    // Load existing attachments if editing (parallel mode starts fresh — each version has its own attachments)
    useEffect(() => {
        if (article?.id) {
            if (article?.versioning_mode === 'parallel') {
                setExistingAttachments([]);
                return;
            }
            fetch(`/api/knowledge-base/${article.id}/attachments`, {
                headers: window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username }
            })
                .then(res => res.json())
                .then(data => {
                    if (data.success && data.attachments) {
                        setExistingAttachments(data.attachments);
                    }
                })
                .catch(err => console.error('Error loading attachments:', err));
        }
    }, [article?.id]);

    // Fetch users list, roles list, and ancestor permissions for access control UI
    useEffect(() => {
        fetch('/api/knowledge-base/users-list', {
            headers: window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username }
        })
        .then(res => res.json())
        .then(data => { if (data.success) setAllUsers(data.users || []); })
        .catch(err => console.error('Error loading users:', err));

        fetch('/api/knowledge-base/roles-list', {
            headers: window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username }
        })
        .then(res => res.json())
        .then(data => { if (data.success) setAllRoles(data.roles || []); })
        .catch(err => console.error('Error loading roles:', err));

        fetch('/api/knowledge-base/brands-list', {
            headers: window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username }
        })
        .then(res => res.json())
        .then(data => { if (data.success) setAllBrands(data.brands || []); })
        .catch(err => console.error('Error loading brands:', err));

        const parentId = article?.parent_id || formData.parent_id;
        if (parentId) {
            fetch(`/api/knowledge-base/ancestor-permissions/${parentId}`, {
                headers: window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username }
            })
            .then(res => res.json())
            .then(data => { if (data.success) setAncestorPerms(data.permissions); })
            .catch(err => console.error('Error loading ancestor permissions:', err));
        }
    }, []);

    // Auto-select ancestor-restricted properties/users/roles (inherited = locked, non-removable)
    useEffect(() => {
        if (!ancestorPerms) return;
        setFormData(prev => {
            const updated = { ...prev };
            if (ancestorPerms.applies_to_properties) {
                const inherited = new Set(ancestorPerms.applies_to_properties);
                const current = new Set(prev.applies_to_properties);
                const merged = [...new Set([...inherited, ...current])];
                if (merged.length !== current.size) updated.applies_to_properties = merged;
            }
            if (ancestorPerms.allowed_users) {
                const inherited = new Set(ancestorPerms.allowed_users);
                const current = new Set(prev.allowed_users);
                const merged = [...new Set([...inherited, ...current])];
                if (merged.length !== current.size) updated.allowed_users = merged;
            }
            if (ancestorPerms.allowed_roles) {
                const inherited = new Set(ancestorPerms.allowed_roles);
                const current = new Set(prev.allowed_roles);
                const merged = [...new Set([...inherited, ...current])];
                if (merged.length !== current.size) updated.allowed_roles = merged;
            }
            if (ancestorPerms.allowed_brands) {
                const inherited = new Set(ancestorPerms.allowed_brands);
                const current = new Set(prev.allowed_brands || []);
                const merged = [...new Set([...inherited, ...current])];
                if (merged.length !== current.size) updated.allowed_brands = merged;
            }
            return updated;
        });
    }, [ancestorPerms]);

    const handleFileSelect = (e) => {
        const files = Array.from(e.target.files);
        setSelectedFiles(prev => [...prev, ...files]);
    };

    const removeSelectedFile = (idx) => {
        setSelectedFiles(prev => prev.filter((_, i) => i !== idx));
    };

    const handleSubmit = async (e) => {
        e.preventDefault();

        // Validate required fields (title, and content-or-attachments for documents)
        const allAttachments = [
            ...(existingAttachments || []),
            ...(selectedFiles || [])
        ];
        const errors = (window.KBComponents && KBComponents.validateKBForm)
            ? KBComponents.validateKBForm(formData, allAttachments)
            : [];
        if (errors.length > 0) {
            window.otoNotify?.toast(errors.join('\n'), 'error');
            return;
        }

        // Build category path from parent folders
        let category = 'General';
        if (kbPath.length > 0) {
            category = kbPath.map(p => p.title).concat(formData.title).join('/');
        } else if (formData.title) {
            category = formData.title;
        }

        // First, save the article/folder
        const itemData = {
            title: formData.title,
            content: formData.content,
            category: category,
            parent_id: formData.parent_id,
            is_folder: formData.is_folder,
            applies_to_properties: formData.applies_to_properties,
            allowed_users: formData.allowed_users,
            allowed_roles: formData.allowed_roles,
            allowed_brands: formData.allowed_brands || [],
            tags: formData.tags,
            versioning_mode: formData.versioning_mode,
            metadata: {
                audience: formData.audience || undefined,
                department: formData.department || undefined
            }
        };

        try {
            // Save item first
            const saveResult = await onSave(itemData);
            const itemId = saveResult?.data?.id || article?.id;

            // If there are files to upload and we have an item ID (only for documents, not folders)
            if (selectedFiles.length > 0 && itemId && !formData.is_folder) {
                for (const file of selectedFiles) {
                    const formData = new FormData();
                    formData.append('file', file);

                    await fetch(`/api/knowledge-base/${itemId}/attachments`, {
                        method: 'POST',
                        headers: {
                            'X-OTO-User': currentUser.Username
                        },
                        body: formData
                    });
                }
            }

            // Close modal after success
            onClose();
        } catch (error) {
            console.error('Error saving:', error);
            window.otoNotify?.toast('Error saving. Please try again.', 'error');
        }
    };

    // Compute available property list (respecting ancestor restrictions)
    const availableProperties = (() => {
        const props = ancestorPerms?.applies_to_properties
            ? (userProperties || []).filter(p => ancestorPerms.applies_to_properties.includes(p.property_code))
            : (userProperties || []);
        return props;
    })();

    // Filter properties by search
    const filteredProperties = availableProperties.filter(p => {
        if (!propertySearch.trim()) return true;
        const q = propertySearch.toLowerCase();
        return (p.property_code || '').toLowerCase().includes(q) || (p.name || '').toLowerCase().includes(q);
    });

    // Compute visible users: filter by selected properties first, then by search
    const propertyFilteredUsers = (() => {
        let users = ancestorPerms?.allowed_users
            ? allUsers.filter(u => ancestorPerms.allowed_users.includes(u.username))
            : allUsers;
        // If properties are selected on this item, further filter to users at those properties
        if (formData.applies_to_properties.length > 0) {
            users = users.filter(u =>
                (u.property_code && formData.applies_to_properties.includes(u.property_code))
                || (u.properties || []).some(pc => formData.applies_to_properties.includes(pc))
            );
        }
        return users;
    })();

    // Then apply text search on top
    const filteredUsers = propertyFilteredUsers.filter(u => {
        if (!userSearch.trim()) return true;
        const q = userSearch.toLowerCase();
        return (u.username || '').toLowerCase().includes(q)
            || (u.first_name || '').toLowerCase().includes(q)
            || (u.last_name || '').toLowerCase().includes(q)
            || (`${u.first_name} ${u.last_name}`).toLowerCase().includes(q);
    });

    // Compute available roles (respecting ancestor restrictions)
    const availableRoles = ancestorPerms?.allowed_roles
        ? allRoles.filter(r => ancestorPerms.allowed_roles.includes(r.id))
        : allRoles;

    // Filter roles by search
    const filteredRoles = availableRoles.filter(r => {
        if (!roleSearch.trim()) return true;
        const q = roleSearch.toLowerCase();
        return (r.display_name || '').toLowerCase().includes(q) || (r.name || '').toLowerCase().includes(q);
    });

    return (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
            <div className="bg-white rounded-xl shadow-xl max-w-3xl w-full max-h-[90vh] overflow-y-auto border border-gray-200">
                <div className="p-6">
                    {/* Header */}
                    <div className="flex items-start justify-between gap-4 mb-6">
                        <div>
                            <h2 className="text-2xl font-bold text-gray-900">
                                {isEditing ? (article.is_folder ? 'Edit Folder' : 'Edit Document') : 'Create New'}
                            </h2>
                            {locationPath && (
                                <div className="text-sm text-gray-600 mt-1 flex items-center gap-2">
                                    <span className="text-gray-400">📍</span>
                                    <span className="font-medium">{locationPath}</span>
                                </div>
                            )}
                        </div>
                        <button
                            type="button"
                            onClick={onClose}
                            className="px-3 py-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50 transition"
                            disabled={saving}
                        >
                            ×
                        </button>
                    </div>

                    <form onSubmit={handleSubmit} className="space-y-5">
                        {/* Tab Bar — hidden when only 1 tab */}
                        {tabs.length > 1 && (
                            <div className="flex gap-2 sticky top-0 bg-white z-10 pb-3 -mt-1 border-b border-gray-200">
                                {tabs.map(tab => (
                                    <button
                                        key={tab.id}
                                        type="button"
                                        onClick={() => setActiveTab(tab.id)}
                                        className={`px-4 py-2 rounded-lg text-sm font-medium transition-colors ${
                                            activeTab === tab.id
                                                ? 'bg-primary text-white'
                                                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                                        }`}
                                    >
                                        {tab.label}
                                    </button>
                                ))}
                            </div>
                        )}

                        {/* ═══ Content Tab ═══ */}
                        {activeTab === 'content' && (<>
                        {/* Type Selection (only when creating new) */}
                        {!isEditing && (
                            <div className="bg-primary/5 border-2 border-primary/20 rounded-xl p-4">
                                <label className="block text-sm font-semibold text-gray-900 mb-3">
                                    What do you want to create?
                                </label>
                                <div className="grid grid-cols-2 gap-3">
                                    <button
                                        type="button"
                                        onClick={() => setFormData({ ...formData, is_folder: false, versioning_mode: 'history' })}
                                        className={`p-4 rounded-xl border-2 transition ${!formData.is_folder
                                                ? 'border-primary bg-primary/10 text-primary'
                                                : 'border-gray-300 bg-white text-gray-700 hover:border-gray-400'
                                            }`}
                                    >
                                        <div className="text-3xl mb-2">📄</div>
                                        <div className="font-semibold">Document</div>
                                        <div className="text-xs mt-1 opacity-75">Article with content & attachments</div>
                                    </button>
                                    <button
                                        type="button"
                                        onClick={() => setFormData({ ...formData, is_folder: true, versioning_mode: 'none', content: '' })}
                                        className={`p-4 rounded-xl border-2 transition ${formData.is_folder
                                                ? 'border-primary bg-primary/10 text-primary'
                                                : 'border-gray-300 bg-white text-gray-700 hover:border-gray-400'
                                            }`}
                                    >
                                        <div className="text-3xl mb-2">📁</div>
                                        <div className="font-semibold">Subfolder</div>
                                        <div className="text-xs mt-1 opacity-75">Organize more documents</div>
                                    </button>
                                </div>
                            </div>
                        )}

                        {/* Title */}
                        <div>
                            <label className="block text-sm font-semibold text-gray-900 mb-2">
                                {formData.is_folder ? 'Folder Name' : 'Document Title'} <span className="text-red-500">*</span>
                            </label>
                            <input
                                type="text"
                                value={formData.title}
                                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                                className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-transparent"
                                placeholder={formData.is_folder ? "e.g., Requirements" : "e.g., CapEx Guidelines 2025"}
                                required
                            />
                        </div>

                        {/* Content (only for documents) — require either content OR at least one attachment */}
                        {!formData.is_folder && (
                            <div>
                                <label className="block text-sm font-semibold text-gray-900 mb-2">
                                    Content
                                </label>
                                <textarea
                                    value={formData.content}
                                    onChange={(e) => setFormData({ ...formData, content: e.target.value })}
                                    rows="8"
                                    className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-transparent font-mono text-sm"
                                    placeholder="Write your document content here, and/or upload files below. At least one is required."
                                />
                                <p className="text-xs text-gray-500 mt-1">Add text and/or upload files below. You must provide at least one.</p>
                            </div>
                        )}

                        {/* Folder Description (only for folders) */}
                        {formData.is_folder && (
                            <div>
                                <label className="block text-sm font-semibold text-gray-900 mb-2">
                                    Description (optional)
                                </label>
                                <input
                                    type="text"
                                    value={formData.content}
                                    onChange={(e) => setFormData({ ...formData, content: e.target.value })}
                                    className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-transparent"
                                    placeholder="Brief description of what's in this folder"
                                />
                            </div>
                        )}

                        {/* Versioning (only for documents) — compact, no history button */}
                        {!formData.is_folder && (
                            <div>
                                <label className="block text-sm font-semibold text-gray-900 mb-2">
                                    Version Strategy
                                </label>
                                <select
                                    value={formData.versioning_mode}
                                    onChange={(e) => setFormData({ ...formData, versioning_mode: e.target.value })}
                                    className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-transparent bg-white"
                                >
                                    <option value="history">History Mode (v1, v2, v3 - each edit creates new version)</option>
                                    <option value="parallel">Parallel Mode (2025, 2026 - versions coexist)</option>
                                    <option value="none">No Versioning (simple document)</option>
                                </select>
                                <p className="text-xs text-gray-500 mt-1">
                                    {formData.versioning_mode === 'history' && '✓ Each edit creates a new version. Good for evolving documents.'}
                                    {formData.versioning_mode === 'parallel' && '✓ Multiple versions coexist. Good for yearly calendars.'}
                                    {formData.versioning_mode === 'none' && '✓ Simple document with no version tracking.'}
                                </p>
                                {!formData.is_folder && (formData.versioning_mode === 'history' || formData.versioning_mode === 'parallel') && isEditing && (
                                    <button
                                        type="button"
                                        onClick={async () => {
                                            try {
                                                const res = await fetch(`/api/knowledge-base/${article.id}/history`, {
                                                    headers: window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username }
                                                });
                                                if (res.ok) {
                                                    const data = await res.json();
                                                    if (data.history && data.history.length > 0 && typeof onOpenHistory === 'function') {
                                                        onOpenHistory(article.id, data.history);
                                                    } else if (data.history && data.history.length > 0) {
                                                        window.otoNotify?.toast('History viewer is not available in this context.', 'info');
                                                    } else {
                                                        window.otoNotify?.toast('No version history yet. History will be created after the first edit.', 'info');
                                                    }
                                                } else {
                                                    window.otoNotify?.toast('Could not load version history', 'error');
                                                }
                                            } catch (error) {
                                                console.error('Error loading history:', error);
                                                window.otoNotify?.toast('Error loading version history', 'error');
                                            }
                                        }}
                                        className="text-sm text-primary hover:underline font-medium mt-1"
                                    >
                                        📚 History
                                    </button>
                                )}
                            </div>
                        )}

                        {/* File Attachments (only for documents) */}
                        {!formData.is_folder && (
                            <div>
                                <label className="block text-sm font-semibold text-gray-900 mb-2">
                                    Attachments
                                </label>

                                {/* Existing attachments */}
                                {existingAttachments.length > 0 && (
                                    <div className="mb-3 space-y-2">
                                        {existingAttachments.map(att => {
                                            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 (
                                                <a
                                                    key={att.id}
                                                    href={`/api/knowledge-base/${article.id}/attachments/${att.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">
                                                            {att.original_filename || att.filename || 'Attachment'}
                                                        </div>
                                                        {att.file_size && (
                                                            <div className="text-xs text-gray-500 mt-0.5">{formatFileSize(att.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>
                                )}

                                {/* New files */}
                                {selectedFiles.length > 0 && (
                                    <div className="mb-3 space-y-2">
                                        {selectedFiles.map((file, idx) => (
                                            <div key={idx} className="flex items-center gap-2 text-sm bg-primary/5 p-2 rounded-xl">
                                                <span className="text-primary">📎</span>
                                                <span className="flex-1 font-medium">{file.name}</span>
                                                <span className="text-xs text-primary">{(file.size / 1024).toFixed(1)} KB</span>
                                                <button
                                                    type="button"
                                                    onClick={() => removeSelectedFile(idx)}
                                                    className="text-red-600 hover:text-red-800 text-xs px-2"
                                                >
                                                    Remove
                                                </button>
                                            </div>
                                        ))}
                                    </div>
                                )}

                                <input
                                    type="file"
                                    onChange={handleFileSelect}
                                    multiple
                                    className="w-full px-4 py-3 border-2 border-dashed border-gray-300 rounded-xl hover:border-primary transition cursor-pointer"
                                />
                                <p className="text-xs text-gray-500 mt-1">
                                    Upload PDFs, Word docs, or other files. Text from documents is extracted for search and AI.
                                </p>
                            </div>
                        )}

                        {/* Tags (moved from Details tab) */}
                        <div>
                            <div className="flex items-center justify-between gap-2 mb-2">
                                <label className="block text-sm font-semibold text-gray-900">
                                    Tags (optional)
                                </label>
                                {!formData.is_folder && currentUser?.Username && (
                                    <button
                                        type="button"
                                        onClick={async () => {
                                            try {
                                                const params = new URLSearchParams({ title: formData.title || '', content: (formData.content || '').substring(0, 2000) });
                                                const res = await fetch(`/api/knowledge-base/suggest-tags?${params}`, { headers: window.getApiHeaders ? window.getApiHeaders(currentUser.Username) : { 'X-OTO-User': currentUser.Username } });
                                                if (res.ok) {
                                                    const data = await res.json();
                                                    if (data.suggested_tags && data.suggested_tags.length) {
                                                        const existing = formData.tags || [];
                                                        const merged = [...new Set([...existing, ...data.suggested_tags])];
                                                        setFormData({ ...formData, tags: merged });
                                                    }
                                                }
                                            } catch (e) { console.error(e); }
                                        }}
                                        className="text-sm text-primary hover:underline font-medium"
                                    >
                                        Suggest tags
                                    </button>
                                )}
                            </div>
                            <KBComponents.TagsInput
                                tags={formData.tags}
                                onChange={(newTags) => setFormData({ ...formData, tags: newTags })}
                                placeholder="Add tags…"
                            />
                            <p className="text-xs text-gray-500 mt-1">
                                Add one or more tags
                            </p>
                        </div>
                        </>)}

                        {/* ═══ Access Tab ═══ */}
                        {activeTab === 'access' && (<>
                        {/* Inheritance notice for folders */}
                        {formData.is_folder && (
                            <div className="rounded-xl border border-primary/20 bg-primary/5 px-4 py-3 text-sm text-primary">
                                <strong>Inheritance:</strong> Access restrictions flow from root to children. Any restrictions set here will automatically apply to all items inside this folder.
                                Child items can narrow access further, but cannot grant access beyond what this folder allows.
                                {isEditing ? ' Narrowing access here will automatically update all existing children.' : ''}
                            </div>
                        )}
                        {/* Searchable Property Access */}
                        {currentUser.can_manage_knowledge_base && (
                            <div>
                                <label className="block text-sm font-semibold text-gray-900 mb-1">
                                    Property Access
                                </label>
                                <p className="text-xs text-gray-500 mb-2">
                                    Limit which properties can reference this item via the AI assistant. Leave empty for all properties (shared).
                                    {formData.is_folder ? ' Child items will inherit these restrictions and cannot exceed them.' : ''}
                                </p>
                                {ancestorPerms?.applies_to_properties && (
                                    <div className="text-xs text-amber-700 font-medium mb-2 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2">
                                        Inherited from <strong>{ancestorPerms.properties_restricted_by?.title || 'parent folder'}</strong> — restricted to: {ancestorPerms.applies_to_properties.join(', ')}.
                                        These cannot be removed.
                                    </div>
                                )}

                                {/* Selected property chips */}
                                {formData.applies_to_properties.length > 0 && (
                                    <div className="flex flex-wrap gap-1.5 mb-2">
                                        {formData.applies_to_properties.map(code => {
                                            const prop = availableProperties.find(p => p.property_code === code);
                                            const isInherited = ancestorPerms?.applies_to_properties?.includes(code);
                                            return (
                                                <span key={code} className={`inline-flex items-center gap-1 ${isInherited ? 'pl-2 pr-2.5' : 'pl-2.5 pr-1'} py-1 rounded-full text-xs font-medium ${isInherited ? 'bg-amber-100 text-amber-800 border border-amber-300' : 'bg-primary/10 text-primary'}`}>
                                                    {isInherited && <svg className="w-3 h-3 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg>}
                                                    {prop ? `${prop.property_code} — ${prop.name}` : code}
                                                    {!isInherited && (
                                                        <button
                                                            type="button"
                                                            onClick={() => setFormData({ ...formData, applies_to_properties: formData.applies_to_properties.filter(c => c !== code) })}
                                                            className="p-0.5 rounded-full hover:bg-primary/20 transition"
                                                        >
                                                            <svg className="w-3.5 h-3.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>
                                                    )}
                                                </span>
                                            );
                                        })}
                                        {formData.applies_to_properties.some(c => !ancestorPerms?.applies_to_properties?.includes(c)) && (
                                            <button
                                                type="button"
                                                onClick={() => setFormData({ ...formData, applies_to_properties: ancestorPerms?.applies_to_properties || [] })}
                                                className="text-xs text-gray-500 hover:text-red-600 ml-1"
                                            >
                                                Clear added
                                            </button>
                                        )}
                                        {!ancestorPerms?.applies_to_properties && (
                                            <button
                                                type="button"
                                                onClick={() => setFormData({ ...formData, applies_to_properties: [] })}
                                                className="text-xs text-gray-500 hover:text-red-600 ml-1"
                                            >
                                                Clear all
                                            </button>
                                        )}
                                    </div>
                                )}

                                {/* Search input */}
                                <input
                                    type="text"
                                    value={propertySearch}
                                    onChange={(e) => setPropertySearch(e.target.value)}
                                    placeholder="Search properties..."
                                    className="w-full px-3 py-2 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-primary focus:border-transparent mb-1"
                                />

                                {/* Checkbox list */}
                                <div className="border border-gray-200 rounded-xl max-h-48 overflow-y-auto">
                                    {filteredProperties.length === 0 && (
                                        <p className="text-xs text-gray-400 px-3 py-2">No properties match your search.</p>
                                    )}
                                    {filteredProperties.map(p => {
                                        const code = p.property_code;
                                        const checked = formData.applies_to_properties.includes(code);
                                        const isInherited = ancestorPerms?.applies_to_properties?.includes(code);
                                        return (
                                            <label key={code} className={`flex items-center gap-2 px-3 py-1.5 text-sm border-b border-gray-100 last:border-b-0 ${isInherited && checked ? 'bg-amber-50 cursor-default' : 'hover:bg-gray-50 cursor-pointer'}`}>
                                                <input
                                                    type="checkbox"
                                                    checked={checked}
                                                    disabled={isInherited && checked}
                                                    onChange={() => {
                                                        if (isInherited && checked) return;
                                                        const next = checked
                                                            ? formData.applies_to_properties.filter(c => c !== code)
                                                            : [...formData.applies_to_properties, code];
                                                        setFormData({ ...formData, applies_to_properties: next });
                                                    }}
                                                    className="rounded border-gray-300 text-primary focus:ring-primary"
                                                />
                                                <span className={isInherited && checked ? 'text-amber-800' : ''}>{code} — {p.name}{isInherited && checked ? ' (inherited)' : ''}</span>
                                            </label>
                                        );
                                    })}
                                </div>
                            </div>
                        )}

                        {/* Searchable Role Access */}
                        {currentUser.can_manage_knowledge_base && (
                            <div>
                                <label className="block text-sm font-semibold text-gray-900 mb-1">
                                    Role Access
                                </label>
                                <p className="text-xs text-gray-500 mb-2">
                                    Limit which roles can reference this item via the AI assistant. Leave empty for all roles. System and Administrator always have access.
                                    {formData.is_folder ? ' Child items will inherit these restrictions and cannot exceed them.' : ''}
                                </p>
                                {ancestorPerms?.allowed_roles && (
                                    <div className="text-xs text-amber-700 font-medium mb-2 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2">
                                        Inherited from <strong>{ancestorPerms.roles_restricted_by?.title || 'parent folder'}</strong> — restricted to: {ancestorPerms.allowed_roles.map(rid => { const r = allRoles.find(x => x.id === rid); return r ? r.display_name : `Role #${rid}`; }).join(', ')}.
                                        These cannot be removed.
                                    </div>
                                )}

                                {/* Selected role chips */}
                                {(formData.allowed_roles || []).length > 0 && (
                                    <div className="flex flex-wrap gap-1.5 mb-2">
                                        {formData.allowed_roles.map(roleId => {
                                            const role = allRoles.find(r => r.id === roleId);
                                            const isInherited = ancestorPerms?.allowed_roles?.includes(roleId);
                                            return (
                                                <span key={roleId} className={`inline-flex items-center gap-1 ${isInherited ? 'pl-2 pr-2.5' : 'pl-2.5 pr-1'} py-1 rounded-full text-xs font-medium ${isInherited ? 'bg-amber-100 text-amber-800 border border-amber-300' : 'bg-primary/10 text-primary'}`}>
                                                    {isInherited && <svg className="w-3 h-3 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg>}
                                                    {role ? role.display_name : `Role #${roleId}`}
                                                    {!isInherited && (
                                                        <button
                                                            type="button"
                                                            onClick={() => setFormData({ ...formData, allowed_roles: formData.allowed_roles.filter(r => r !== roleId) })}
                                                            className="p-0.5 rounded-full hover:bg-primary/20 transition"
                                                        >
                                                            <svg className="w-3.5 h-3.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>
                                                    )}
                                                </span>
                                            );
                                        })}
                                        {formData.allowed_roles.some(r => !ancestorPerms?.allowed_roles?.includes(r)) && (
                                            <button
                                                type="button"
                                                onClick={() => setFormData({ ...formData, allowed_roles: ancestorPerms?.allowed_roles || [] })}
                                                className="text-xs text-gray-500 hover:text-red-600 ml-1"
                                            >
                                                Clear added
                                            </button>
                                        )}
                                        {!ancestorPerms?.allowed_roles && (
                                            <button
                                                type="button"
                                                onClick={() => setFormData({ ...formData, allowed_roles: [] })}
                                                className="text-xs text-gray-500 hover:text-red-600 ml-1"
                                            >
                                                Clear all
                                            </button>
                                        )}
                                    </div>
                                )}

                                {/* Search input */}
                                <input
                                    type="text"
                                    value={roleSearch}
                                    onChange={(e) => setRoleSearch(e.target.value)}
                                    placeholder="Search roles..."
                                    className="w-full px-3 py-2 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-primary focus:border-transparent mb-1"
                                />

                                {/* Checkbox list */}
                                <div className="border border-gray-200 rounded-xl max-h-48 overflow-y-auto">
                                    {filteredRoles.length === 0 && (
                                        <p className="text-xs text-gray-400 px-3 py-2">No roles match your search.</p>
                                    )}
                                    {filteredRoles.map(r => {
                                        const checked = (formData.allowed_roles || []).includes(r.id);
                                        const isInherited = ancestorPerms?.allowed_roles?.includes(r.id);
                                        return (
                                            <label key={r.id} className={`flex items-center gap-2 px-3 py-1.5 text-sm border-b border-gray-100 last:border-b-0 ${isInherited && checked ? 'bg-amber-50 cursor-default' : 'hover:bg-gray-50 cursor-pointer'}`}>
                                                <input
                                                    type="checkbox"
                                                    checked={checked}
                                                    disabled={isInherited && checked}
                                                    onChange={() => {
                                                        if (isInherited && checked) return;
                                                        const next = checked
                                                            ? (formData.allowed_roles || []).filter(x => x !== r.id)
                                                            : [...(formData.allowed_roles || []), r.id];
                                                        setFormData({ ...formData, allowed_roles: next });
                                                    }}
                                                    className="rounded border-gray-300 text-primary focus:ring-primary"
                                                />
                                                <span className={isInherited && checked ? 'text-amber-800' : ''}>{r.display_name}{isInherited && checked ? ' (inherited)' : ''}</span>
                                            </label>
                                        );
                                    })}
                                </div>
                            </div>
                        )}

                        {/* Searchable User Access (cascaded by property selection) */}
                        {currentUser.can_manage_knowledge_base && (
                            <div>
                                <label className="block text-sm font-semibold text-gray-900 mb-1">
                                    User Access
                                </label>
                                <p className="text-xs text-gray-500 mb-2">
                                    Limit which users can reference this item via the AI assistant. Leave empty for all users.
                                    {formData.applies_to_properties.length > 0 ? ' Filtered to users belonging to the selected properties.' : ''}
                                </p>
                                {ancestorPerms?.allowed_users && (
                                    <div className="text-xs text-amber-700 font-medium mb-2 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2">
                                        Inherited from <strong>{ancestorPerms.users_restricted_by?.title || 'parent folder'}</strong> — restricted to: {ancestorPerms.allowed_users.join(', ')}.
                                        These cannot be removed.
                                    </div>
                                )}

                                {/* Selected user chips */}
                                {(formData.allowed_users || []).length > 0 && (
                                    <div className="flex flex-wrap gap-1.5 mb-2">
                                        {formData.allowed_users.map(username => {
                                            const user = allUsers.find(u => u.username === username);
                                            const isInherited = ancestorPerms?.allowed_users?.includes(username);
                                            return (
                                                <span key={username} className={`inline-flex items-center gap-1 ${isInherited ? 'pl-2 pr-2.5' : 'pl-2.5 pr-1'} py-1 rounded-full text-xs font-medium ${isInherited ? 'bg-amber-100 text-amber-800 border border-amber-300' : 'bg-primary/10 text-primary'}`}>
                                                    {isInherited && <svg className="w-3 h-3 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg>}
                                                    {user ? `${user.first_name} ${user.last_name}` : username}
                                                    {!isInherited && (
                                                        <button
                                                            type="button"
                                                            onClick={() => setFormData({ ...formData, allowed_users: formData.allowed_users.filter(u => u !== username) })}
                                                            className="p-0.5 rounded-full hover:bg-primary/20 transition"
                                                        >
                                                            <svg className="w-3.5 h-3.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>
                                                    )}
                                                </span>
                                            );
                                        })}
                                        {formData.allowed_users.some(u => !ancestorPerms?.allowed_users?.includes(u)) && (
                                            <button
                                                type="button"
                                                onClick={() => setFormData({ ...formData, allowed_users: ancestorPerms?.allowed_users || [] })}
                                                className="text-xs text-gray-500 hover:text-red-600 ml-1"
                                            >
                                                Clear added
                                            </button>
                                        )}
                                        {!ancestorPerms?.allowed_users && (
                                            <button
                                                type="button"
                                                onClick={() => setFormData({ ...formData, allowed_users: [] })}
                                                className="text-xs text-gray-500 hover:text-red-600 ml-1"
                                            >
                                                Clear all
                                            </button>
                                        )}
                                    </div>
                                )}

                                {/* Search input */}
                                <input
                                    type="text"
                                    value={userSearch}
                                    onChange={(e) => setUserSearch(e.target.value)}
                                    placeholder="Search users..."
                                    className="w-full px-3 py-2 border border-gray-300 rounded-xl text-sm focus:ring-2 focus:ring-primary focus:border-transparent mb-1"
                                />

                                {/* Checkbox list */}
                                <div className="border border-gray-200 rounded-xl max-h-48 overflow-y-auto">
                                    {propertyFilteredUsers.length === 0 && formData.applies_to_properties.length > 0 && (
                                        <p className="text-xs text-gray-400 px-3 py-2">No users belong to the selected properties. Try selecting different properties or clearing the property filter.</p>
                                    )}
                                    {propertyFilteredUsers.length > 0 && filteredUsers.length === 0 && (
                                        <p className="text-xs text-gray-400 px-3 py-2">No users match your search.</p>
                                    )}
                                    {filteredUsers.map(u => {
                                        const checked = (formData.allowed_users || []).includes(u.username);
                                        const isInherited = ancestorPerms?.allowed_users?.includes(u.username);
                                        return (
                                            <label key={u.username} className={`flex items-center gap-2 px-3 py-1.5 text-sm border-b border-gray-100 last:border-b-0 ${isInherited && checked ? 'bg-amber-50 cursor-default' : 'hover:bg-gray-50 cursor-pointer'}`}>
                                                <input
                                                    type="checkbox"
                                                    checked={checked}
                                                    disabled={isInherited && checked}
                                                    onChange={() => {
                                                        if (isInherited && checked) return;
                                                        const next = checked
                                                            ? (formData.allowed_users || []).filter(x => x !== u.username)
                                                            : [...(formData.allowed_users || []), u.username];
                                                        setFormData({ ...formData, allowed_users: next });
                                                    }}
                                                    className="rounded border-gray-300 text-primary focus:ring-primary"
                                                />
                                                <span className={isInherited && checked ? 'text-amber-800' : ''}>{u.first_name} {u.last_name} ({u.username}){isInherited && checked ? ' (inherited)' : ''}</span>
                                            </label>
                                        );
                                    })}
                                </div>
                            </div>
                        )}

                        {/* Brand Access (Marriott, Hilton, Hyatt, etc. from properties) */}
                        {currentUser.can_manage_knowledge_base && (
                            <div>
                                <label className="block text-sm font-semibold text-gray-900 mb-1">
                                    Brand Access
                                </label>
                                <p className="text-xs text-gray-500 mb-2">
                                    Limit which brands (e.g. Marriott, Hilton, Hyatt) can reference this item. Leave empty for all brands. Users see items only for brands of properties they have access to.
                                    {formData.is_folder ? ' Child items will inherit these restrictions and cannot exceed them.' : ''}
                                </p>
                                {ancestorPerms?.allowed_brands && ancestorPerms.allowed_brands.length > 0 && (
                                    <div className="text-xs text-amber-700 font-medium mb-2 bg-amber-50 border border-amber-200 rounded-lg px-3 py-2">
                                        Inherited from <strong>{ancestorPerms.brands_restricted_by?.title || 'parent folder'}</strong> — restricted to: {ancestorPerms.allowed_brands.join(', ')}.
                                        These cannot be removed.
                                    </div>
                                )}

                                {(formData.allowed_brands || []).length > 0 && (
                                    <div className="flex flex-wrap gap-1.5 mb-2">
                                        {(formData.allowed_brands || []).map(brand => {
                                            const isInherited = ancestorPerms?.allowed_brands?.includes(brand);
                                            return (
                                                <span key={brand} className={`inline-flex items-center gap-1 ${isInherited ? 'pl-2 pr-2.5' : 'pl-2.5 pr-1'} py-1 rounded-full text-xs font-medium ${isInherited ? 'bg-amber-100 text-amber-800 border border-amber-300' : 'bg-primary/10 text-primary'}`}>
                                                    {isInherited && <svg className="w-3 h-3 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" /></svg>}
                                                    {brand}
                                                    {!isInherited && (
                                                        <button
                                                            type="button"
                                                            onClick={() => setFormData({ ...formData, allowed_brands: (formData.allowed_brands || []).filter(b => b !== brand) })}
                                                            className="p-0.5 rounded-full hover:bg-primary/20 transition"
                                                        >
                                                            <svg className="w-3.5 h-3.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>
                                                    )}
                                                </span>
                                            );
                                        })}
                                        {(formData.allowed_brands || []).some(b => !ancestorPerms?.allowed_brands?.includes(b)) && (
                                            <button
                                                type="button"
                                                onClick={() => setFormData({ ...formData, allowed_brands: ancestorPerms?.allowed_brands || [] })}
                                                className="text-xs text-gray-500 hover:text-red-600 ml-1"
                                            >
                                                Clear added
                                            </button>
                                        )}
                                        {!ancestorPerms?.allowed_brands?.length && (
                                            <button
                                                type="button"
                                                onClick={() => setFormData({ ...formData, allowed_brands: [] })}
                                                className="text-xs text-gray-500 hover:text-red-600 ml-1"
                                            >
                                                Clear all
                                            </button>
                                        )}
                                    </div>
                                )}

                                <div className="border border-gray-200 rounded-xl max-h-48 overflow-y-auto">
                                    {allBrands.length === 0 && (
                                        <p className="text-xs text-gray-400 px-3 py-2">No brands in system. Add a brand to properties to see them here.</p>
                                    )}
                                    {allBrands.map(brand => {
                                        const checked = (formData.allowed_brands || []).includes(brand);
                                        const isInherited = ancestorPerms?.allowed_brands?.includes(brand);
                                        return (
                                            <label key={brand} className={`flex items-center gap-2 px-3 py-1.5 text-sm border-b border-gray-100 last:border-b-0 ${isInherited && checked ? 'bg-amber-50 cursor-default' : 'hover:bg-gray-50 cursor-pointer'}`}>
                                                <input
                                                    type="checkbox"
                                                    checked={checked}
                                                    disabled={isInherited && checked}
                                                    onChange={() => {
                                                        if (isInherited && checked) return;
                                                        const next = checked
                                                            ? (formData.allowed_brands || []).filter(b => b !== brand)
                                                            : [...(formData.allowed_brands || []), brand];
                                                        setFormData({ ...formData, allowed_brands: next });
                                                    }}
                                                    className="rounded border-gray-300 text-primary focus:ring-primary"
                                                />
                                                <span className={isInherited && checked ? 'text-amber-800' : ''}>{brand}{isInherited && checked ? ' (inherited)' : ''}</span>
                                            </label>
                                        );
                                    })}
                                </div>
                            </div>
                        )}
                        </>)}

                        {/* Actions — always visible */}
                        <div className="flex items-center justify-end gap-3 pt-4 border-t border-gray-200">
                            <button
                                type="button"
                                onClick={onClose}
                                className="px-6 py-2.5 border border-gray-300 text-gray-700 rounded-xl hover:bg-gray-50 transition"
                                disabled={saving}
                            >
                                Cancel
                            </button>
                            <button
                                type="submit"
                                className="px-6 py-2.5 bg-primary text-white rounded-xl hover:bg-primary-hover transition shadow-sm font-medium disabled:opacity-50"
                                disabled={saving}
                            >
                                {saving ? 'Saving...' : (isEditing ? 'Save Changes' : (formData.is_folder ? 'Create Folder' : 'Create Document'))}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    );
};

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