(function () {
    window.AgentFrontendModules = window.AgentFrontendModules || {};

    window.AgentFrontendModules.createComposerAttachmentsModule = function createComposerAttachmentsModule(deps) {
        const cloudAttachedFiles = [];
        let lastSentContextSnapshot = null;
        let oneDriveMode = 'local';
        let cloudProvider = '';
        let cloudNavStack = [];
        let cloudSelected = new Map();
        let cloudSelectMode = 'files';
        let cloudFolderSelectCallback = null;
        let cloudCurrentFolder = null;
        let uiBound = false;
        let composerDragDepth = 0;

        function closeAttachPopup() {
            if (deps.refs.attachPopup) deps.refs.attachPopup.style.display = 'none';
            if (deps.refs.composerMoreSubmenu) deps.refs.composerMoreSubmenu.style.display = 'none';
        }

        function refreshAttachChips() {
            if (!deps.refs.attachChips) return;
            deps.refs.attachChips.innerHTML = '';
            const hasFiles = !!(deps.refs.fileInput && deps.refs.fileInput.files.length > 0);
            const hasFolder = !!(deps.refs.folderPathInput && deps.refs.folderPathInput.value.trim());
            const hasCloud = cloudAttachedFiles.length > 0;
            if (!hasFiles && !hasFolder && !hasCloud) {
                deps.refs.attachChips.style.display = 'none';
                return;
            }
            deps.refs.attachChips.style.display = 'flex';

            if (hasFiles) {
                for (const file of deps.refs.fileInput.files) {
                    const chip = document.createElement('span');
                    chip.className = 'attach-chip';
                    chip.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><polyline points="13 2 13 9 20 9"/></svg> '
                        + deps.helpers.escapeHtml(file.name);
                    const removeButton = document.createElement('button');
                    removeButton.className = 'attach-chip-remove';
                    removeButton.innerHTML = '&times;';
                    removeButton.title = 'Remove';
                    removeButton.addEventListener('click', () => {
                        deps.refs.fileInput.value = '';
                        if (deps.refs.fileLabel) deps.refs.fileLabel.textContent = 'Attach files';
                        refreshAttachChips();
                    });
                    chip.appendChild(removeButton);
                    deps.refs.attachChips.appendChild(chip);
                }
            }

            if (hasFolder) {
                const chip = document.createElement('span');
                chip.className = 'attach-chip folder';
                const folderPath = deps.refs.folderPathInput.value.trim();
                const display = folderPath.split(/[\\/]/).pop() || folderPath;
                chip.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg> '
                    + deps.helpers.escapeHtml(display);
                chip.title = folderPath;
                const removeButton = document.createElement('button');
                removeButton.className = 'attach-chip-remove';
                removeButton.innerHTML = '&times;';
                removeButton.title = 'Remove folder';
                removeButton.addEventListener('click', () => {
                    deps.refs.folderPathInput.value = '';
                    if (deps.refs.folderClearBtn) deps.refs.folderClearBtn.style.display = 'none';
                    const status = document.getElementById('folder-path-status');
                    if (status) {
                        status.textContent = '';
                        status.className = 'folder-path-status';
                    }
                    refreshAttachChips();
                });
                chip.appendChild(removeButton);
                deps.refs.attachChips.appendChild(chip);
            }

            if (hasCloud) {
                for (let index = 0; index < cloudAttachedFiles.length; index += 1) {
                    const attachedFile = cloudAttachedFiles[index];
                    const chip = document.createElement('span');
                    chip.className = 'attach-chip cloud';
                    const providerLabel = attachedFile.provider === 'google_drive' ? 'Drive' : 'OneDrive';
                    const cloudIcon = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z"/></svg>';
                    chip.innerHTML = `${cloudIcon} ${deps.helpers.escapeHtml(attachedFile.name)} <span style="opacity:.5;font-size:0.7rem">(${providerLabel})</span>`;
                    chip.title = `${providerLabel}: ${attachedFile.name}`;
                    const removeButton = document.createElement('button');
                    removeButton.className = 'attach-chip-remove';
                    removeButton.innerHTML = '&times;';
                    removeButton.title = 'Remove';
                    removeButton.addEventListener('click', () => {
                        cloudAttachedFiles.splice(index, 1);
                        refreshAttachChips();
                    });
                    chip.appendChild(removeButton);
                    deps.refs.attachChips.appendChild(chip);
                }
            }
        }

        function syncLocalFileSelection(files, options = {}) {
            if (!deps.refs.fileInput || typeof DataTransfer !== 'function') return false;
            const incomingFiles = Array.from(files || []).filter((file) => file instanceof File);
            if (!incomingFiles.length) return false;
            const transfer = new DataTransfer();
            const seen = new Set();
            const addUnique = (file) => {
                const key = `${file.name}::${file.size}::${file.lastModified}`;
                if (seen.has(key)) return;
                seen.add(key);
                transfer.items.add(file);
            };
            if (options.append !== false) {
                Array.from(deps.refs.fileInput.files || []).forEach(addUnique);
            }
            incomingFiles.forEach(addUnique);
            deps.refs.fileInput.files = transfer.files;
            deps.refs.fileInput.dispatchEvent(new Event('change', { bubbles: true }));
            return true;
        }

        function composerDropHasFiles(event) {
            const types = Array.from(event?.dataTransfer?.types || []);
            return types.includes('Files');
        }

        function setComposerDropActive(active) {
            if (!deps.refs.composerInputRow) return;
            deps.refs.composerInputRow.classList.toggle('composer-input-row--dragover', !!active);
        }

        function buildFolderAttachmentContext(data) {
            const root = String(data?.root || '').trim();
            const files = Array.isArray(data?.files) ? data.files : [];
            const fileCount = Number.isFinite(Number(data?.file_count)) ? Number(data.file_count) : files.length;
            const tree = files.map((file) => {
                const kb = ((Number(file?.size) || 0) / 1024).toFixed(1);
                const note = file?.readable === false ? ' [binary]' : '';
                const relPath = String(file?.rel || file?.path || '').trim();
                const fullPath = String(file?.path || '').trim();
                return `  ${relPath} (${kb} KB)${note} -> ${fullPath}`;
            }).join('\n');

            const lines = [
                `--- Attached folder: ${root} (${fileCount} files) ---`,
                'The user attached this local folder as reference context.',
                'If you need the contents of a file from this folder, call extract_source with the full path shown below.',
                'Only open files that are relevant to the task. Do not guess file contents from filenames alone.',
            ];

            if (tree) {
                lines.push('', 'File index:', tree);
            } else {
                lines.push('', 'File index: (empty)');
            }

            return lines.join('\n');
        }

        function captureStructuralContextSnapshot(baseSettings = null) {
            const enabledSources = deps.helpers.buildStructuralContextSources(baseSettings).filter((entry) => entry.enabled !== false);
            const groups = new Map();
            enabledSources.forEach((entry) => {
                const provider = deps.helpers.contextUiProvider(entry) || entry.provider || entry.kind || 'context';
                if (!groups.has(provider)) groups.set(provider, []);
                groups.get(provider).push(entry);
            });
            const providerLines = Array.from(groups.entries())
                .sort((left, right) => deps.helpers.contextProviderSortRank(left[0]) - deps.helpers.contextProviderSortRank(right[0]) || left[0].localeCompare(right[0]))
                .map(([provider, items]) => {
                    const orderedItems = [...items].sort((left, right) => left.path.localeCompare(right.path));
                    const preview = orderedItems.slice(0, 3).map((entry) => entry.path).join(', ');
                    const extraCount = orderedItems.length - Math.min(orderedItems.length, 3);
                    return `${deps.helpers.contextProviderLabel(provider)} (${orderedItems.length}): ${preview}${extraCount > 0 ? `, +${extraCount} more` : ''}`;
                });
            return {
                total: enabledSources.length,
                providerLines,
            };
        }

        function captureComposerContextSnapshot() {
            const localFiles = Array.from(deps.refs.fileInput?.files || []).map((file) => String(file?.name || '').trim()).filter(Boolean);
            const folderPath = String(deps.refs.folderPathInput?.value || '').trim();
            const cloudFiles = cloudAttachedFiles.map((attachedFile) => {
                const source = attachedFile.provider === 'google_drive' ? 'Google Drive' : 'OneDrive';
                return `${attachedFile.name} (${source})`;
            });
            return {
                sessionId: String(deps.state.getViewedHistorySessionId?.() || deps.state.getCurrentSessionId?.() || deps.state.getPreferredConversationSessionId?.() || '').trim(),
                typedContextChars: String(deps.refs.contextInput?.value || '').trim().length,
                localFiles,
                folderPath,
                cloudFiles,
                structuralContext: captureStructuralContextSnapshot(deps.getAppSettings()),
            };
        }

        function storeLastSentContextSnapshot(snapshot) {
            if (!snapshot || typeof snapshot !== 'object') return;
            const structuralContext = snapshot.structuralContext && typeof snapshot.structuralContext === 'object'
                ? snapshot.structuralContext
                : {};
            lastSentContextSnapshot = {
                sessionId: String(snapshot.sessionId || '').trim(),
                typedContextChars: Number(snapshot.typedContextChars || 0),
                localFiles: Array.isArray(snapshot.localFiles) ? snapshot.localFiles.slice() : [],
                folderPath: String(snapshot.folderPath || '').trim(),
                cloudFiles: Array.isArray(snapshot.cloudFiles) ? snapshot.cloudFiles.slice() : [],
                effectiveContextChars: Number(snapshot.effectiveContextChars || 0),
                structuralContext: {
                    total: Number(structuralContext.total || 0),
                    providerLines: Array.isArray(structuralContext.providerLines) ? structuralContext.providerLines.slice() : [],
                },
                sentAt: Date.now(),
            };
        }

        function buildLiveContextSummary() {
            const lines = [];
            lines.push('**Current Context Snapshot**');

            const currentSnapshot = captureComposerContextSnapshot();
            const hasCurrentAttachmentContext = currentSnapshot.localFiles.length > 0
                || !!currentSnapshot.folderPath
                || currentSnapshot.cloudFiles.length > 0;

            lines.push(`- Session: ${currentSnapshot.sessionId || 'none'}`);
            lines.push(`- Typed context field (current): ${currentSnapshot.typedContextChars ? `${currentSnapshot.typedContextChars} chars` : 'empty'}`);
            lines.push(`- Attached files (current): ${currentSnapshot.localFiles.length ? currentSnapshot.localFiles.join(', ') : 'none'}`);
            lines.push(`- Attached folder (current): ${currentSnapshot.folderPath || 'none'}`);
            lines.push(`- Cloud attachments (current): ${currentSnapshot.cloudFiles.length ? currentSnapshot.cloudFiles.join(', ') : 'none'}`);
            lines.push(`- Persistent context from Settings (current): ${currentSnapshot.structuralContext.total ? `${currentSnapshot.structuralContext.total} source(s)` : 'none'}`);
            currentSnapshot.structuralContext.providerLines.forEach((line) => lines.push(`- ${line}`));

            if (!hasCurrentAttachmentContext && lastSentContextSnapshot) {
                lines.push('');
                lines.push('**Last Sent Context (most recent request)**');
                lines.push(`- Session: ${lastSentContextSnapshot.sessionId || 'none'}`);
                lines.push(`- Typed context field: ${lastSentContextSnapshot.typedContextChars ? `${lastSentContextSnapshot.typedContextChars} chars` : 'empty'}`);
                lines.push(`- Attached files: ${lastSentContextSnapshot.localFiles.length ? lastSentContextSnapshot.localFiles.join(', ') : 'none'}`);
                lines.push(`- Attached folder: ${lastSentContextSnapshot.folderPath || 'none'}`);
                lines.push(`- Cloud attachments: ${lastSentContextSnapshot.cloudFiles.length ? lastSentContextSnapshot.cloudFiles.join(', ') : 'none'}`);
                lines.push(`- Persistent context from Settings: ${lastSentContextSnapshot.structuralContext.total ? `${lastSentContextSnapshot.structuralContext.total} source(s)` : 'none'}`);
                lastSentContextSnapshot.structuralContext.providerLines.forEach((line) => lines.push(`- ${line}`));
                lines.push(`- Effective context sent: ${lastSentContextSnapshot.effectiveContextChars ? `${lastSentContextSnapshot.effectiveContextChars} chars` : 'none'}`);
            }

            const emailContextActive = !!(deps.state.getEmailReaderModal?.() || deps.state.getFollowupEmailRow?.());
            const calendarContextActive = !!deps.state.getFollowupCalendarRow?.();
            lines.push(`- Email follow-up context: ${emailContextActive ? 'active' : 'inactive'}`);
            lines.push(`- Calendar follow-up context: ${calendarContextActive ? 'active' : 'inactive'}`);

            const memoryChars = String(deps.state.getRecalledMemoryRaw?.() || '').trim().length;
            lines.push(`- Memory recall in this run: ${memoryChars ? `${memoryChars} chars` : 'none'}`);
            lines.push(`- Integrations enabled: web=${deps.state.getInternetEnabled?.() ? 'on' : 'off'}, email=${deps.state.getEmailEnabled?.() ? 'on' : 'off'}`);

            return lines.join('\n');
        }

        function applyOneDriveMode(mode) {
            oneDriveMode = mode;
            if (deps.refs.onedriveLocalSettings) deps.refs.onedriveLocalSettings.style.display = mode === 'local' ? '' : 'none';
            if (deps.refs.onedriveGraphSettings) deps.refs.onedriveGraphSettings.style.display = mode === 'graph' ? '' : 'none';
        }

        function cloudUpdateStatus(googleOk, microsoftOk) {
            if (deps.refs.attachGoogleDrive) deps.refs.attachGoogleDrive.style.display = googleOk ? '' : 'none';
            if (deps.refs.attachOneDrive) deps.refs.attachOneDrive.style.display = microsoftOk ? '' : 'none';
        }

        function formatSize(bytes) {
            if (!bytes || bytes <= 0) return '';
            if (bytes < 1024) return `${bytes} B`;
            if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
            return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
        }

        function cloudUpdateBreadcrumb(name) {
            if (deps.refs.cloudPath) {
                const parts = cloudNavStack.map((entry) => entry.name).concat(name || 'Root');
                deps.refs.cloudPath.textContent = '/ ' + parts.join(' / ');
            }
            if (deps.refs.cloudBack) deps.refs.cloudBack.disabled = cloudNavStack.length === 0;
        }

        function cloudUpdateFooter() {
            if (cloudSelectMode === 'folder') {
                if (deps.refs.cloudCountLabel) deps.refs.cloudCountLabel.textContent = cloudCurrentFolder?.pathLabel || 'Root';
                if (deps.refs.cloudAttachBtn) {
                    deps.refs.cloudAttachBtn.disabled = !cloudCurrentFolder;
                    deps.refs.cloudAttachBtn.textContent = 'Use this folder';
                }
                return;
            }
            const selectedCount = cloudSelected.size;
            if (deps.refs.cloudCountLabel) {
                deps.refs.cloudCountLabel.textContent = selectedCount === 0
                    ? '0 selected'
                    : `${selectedCount} file${selectedCount > 1 ? 's' : ''} selected`;
            }
            if (deps.refs.cloudAttachBtn) {
                deps.refs.cloudAttachBtn.disabled = selectedCount === 0;
                deps.refs.cloudAttachBtn.textContent = 'Attach selected';
            }
        }

        function closeCloudBrowser() {
            if (deps.refs.cloudOverlay) deps.refs.cloudOverlay.style.display = 'none';
            cloudSelectMode = 'files';
            cloudFolderSelectCallback = null;
            cloudCurrentFolder = null;
            cloudSelected.clear();
            cloudUpdateFooter();
        }

        async function cloudBrowse(folderId, folderName) {
            if (!deps.refs.cloudList) return;
            deps.refs.cloudList.innerHTML = '<div class="cloud-browser-loading">Loading…</div>';
            if (cloudSelectMode === 'files') cloudSelected.clear();
            cloudUpdateFooter();
            try {
                let url;
                if (cloudProvider === 'google_drive') {
                    url = `${deps.getBackendUrl()}/api/cloud-browse/google-drive?folder_id=${encodeURIComponent(folderId || 'root')}`;
                } else if (cloudProvider === 'onedrive_local') {
                    const params = folderId ? `folder_path=${encodeURIComponent(folderId)}` : '';
                    url = `${deps.getBackendUrl()}/api/cloud-browse/onedrive-local?${params}`;
                } else {
                    const params = folderId ? `folder_id=${encodeURIComponent(folderId)}` : '';
                    url = `${deps.getBackendUrl()}/api/cloud-browse/onedrive?${params}`;
                }
                const response = await deps.authFetch(url);
                if (!response.ok) throw new Error(`HTTP ${response.status}`);
                const data = await response.json();
                const items = data.items || [];
                deps.refs.cloudList.innerHTML = '';
                cloudCurrentFolder = {
                    id: folderId || (cloudProvider === 'google_drive' ? 'root' : ''),
                    name: folderName || 'Root',
                    pathLabel: deps.refs.cloudPath
                        ? String(deps.refs.cloudPath.textContent || '').replace(/^\/\s*/, '')
                        : (folderName || 'Root'),
                };
                cloudUpdateFooter();
                if (items.length === 0) {
                    deps.refs.cloudList.innerHTML = '<div class="cloud-browser-empty">This folder is empty</div>';
                    return;
                }
                for (const item of items) {
                    const row = document.createElement('div');
                    row.className = 'cloud-browser-item';
                    row.dataset.id = item.id;
                    row.dataset.name = item.name;
                    row.dataset.isFolder = item.is_folder ? '1' : '0';
                    row.dataset.size = item.size || 0;
                    const sizeLabel = item.is_folder ? '' : formatSize(item.size || 0);
                    const iconSvg = item.is_folder
                        ? '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>'
                        : '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><polyline points="13 2 13 9 20 9"/></svg>';
                    const checkSvg = '<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
                    row.innerHTML = `<span class="cloud-browser-item-icon${item.is_folder ? ' folder-icon' : ''}">${iconSvg}</span>`
                        + (item.is_folder ? '' : `<span class="cloud-browser-item-check">${checkSvg}</span>`)
                        + `<span class="cloud-browser-item-name">${deps.helpers.escapeHtml(item.name)}</span>`
                        + (sizeLabel ? `<span class="cloud-browser-item-size">${sizeLabel}</span>` : '');
                    row.addEventListener('click', () => {
                        if (item.is_folder) {
                            cloudNavStack.push({ id: folderId || 'root', name: folderName || 'Root' });
                            cloudBrowse(item.id, item.name);
                            cloudUpdateBreadcrumb(item.name);
                            return;
                        }
                        if (cloudSelectMode !== 'files') return;
                        if (cloudSelected.has(item.id)) {
                            cloudSelected.delete(item.id);
                            row.classList.remove('selected');
                        } else {
                            cloudSelected.set(item.id, { id: item.id, name: item.name, size: item.size });
                            row.classList.add('selected');
                        }
                        cloudUpdateFooter();
                    });
                    deps.refs.cloudList.appendChild(row);
                }
            } catch (error) {
                deps.refs.cloudList.innerHTML = `<div class="cloud-browser-empty">Error: ${deps.helpers.escapeHtml(error.message)}</div>`;
            }
        }

        function openCloudBrowser(provider, title, options = null) {
            cloudProvider = provider;
            cloudNavStack = [];
            cloudSelected.clear();
            cloudSelectMode = options?.mode === 'folder' ? 'folder' : 'files';
            cloudFolderSelectCallback = typeof options?.onSelectFolder === 'function' ? options.onSelectFolder : null;
            cloudCurrentFolder = null;
            if (deps.refs.cloudTitle) deps.refs.cloudTitle.textContent = title;
            cloudUpdateBreadcrumb('Root');
            cloudUpdateFooter();
            if (deps.refs.cloudOverlay) deps.refs.cloudOverlay.style.display = '';
            cloudBrowse(provider === 'google_drive' ? 'root' : '', 'Root');
        }

        async function bindPickFolder() {
            try {
                const response = await deps.authFetch(`${deps.getBackendUrl()}/api/pick-folder`);
                const data = await response.json();
                if (!data.cancelled && data.path && deps.refs.folderPathInput) {
                    deps.refs.folderPathInput.value = data.path;
                    if (deps.refs.folderClearBtn) deps.refs.folderClearBtn.style.display = '';
                    const status = document.getElementById('folder-path-status');
                    if (status) {
                        status.textContent = '';
                        status.className = 'folder-path-status';
                    }
                    refreshAttachChips();
                }
            } catch (error) {
                console.warn('pick-folder failed:', error);
            }
        }

        function bindUi() {
            if (uiBound) return;
            uiBound = true;

            if (deps.refs.attachBtn && deps.refs.attachPopup) {
                deps.refs.attachBtn.addEventListener('click', (event) => {
                    event.stopPropagation();
                    const isOpen = deps.refs.attachPopup.style.display !== 'none';
                    deps.refs.attachPopup.style.display = isOpen ? 'none' : 'flex';
                    if (isOpen && deps.refs.composerMoreSubmenu) deps.refs.composerMoreSubmenu.style.display = 'none';
                });
                document.addEventListener('click', (event) => {
                    if (deps.refs.attachPopup.style.display !== 'none'
                        && !deps.refs.attachPopup.contains(event.target)
                        && event.target !== deps.refs.attachBtn) {
                        closeAttachPopup();
                    }
                });
                deps.refs.attachPopup.querySelector('[data-action="files"]')?.addEventListener('click', () => {
                    closeAttachPopup();
                    deps.refs.fileInput?.click();
                });
                deps.refs.attachPopup.querySelector('[data-action="folder"]')?.addEventListener('click', async () => {
                    closeAttachPopup();
                    await bindPickFolder();
                });
                deps.refs.attachPopup.querySelector('[data-action="more-toggle"]')?.addEventListener('click', (event) => {
                    event.stopPropagation();
                    if (!deps.refs.composerMoreSubmenu) return;
                    const open = deps.refs.composerMoreSubmenu.style.display !== 'none';
                    deps.refs.composerMoreSubmenu.style.display = open ? 'none' : 'flex';
                });
                deps.refs.attachPopup.querySelector('[data-action="show-context"]')?.addEventListener('click', () => {
                    const summary = buildLiveContextSummary();
                    deps.helpers.appendChatBubble('system', summary);
                    const lastBubble = deps.refs.chatThread?.lastElementChild;
                    if (lastBubble && lastBubble.classList.contains('chat-bubble')) {
                        lastBubble.classList.add('context-snapshot-bubble');
                    }
                    deps.helpers.ensureChatThreadVisibleState();
                    deps.helpers.compactChatThreadLayout();
                    deps.helpers.scrollChatToBottom();
                    closeAttachPopup();
                });
            }

            if (deps.refs.fileInput) {
                deps.refs.fileInput.addEventListener('change', () => {
                    if (!deps.refs.fileLabel) {
                        refreshAttachChips();
                        return;
                    }
                    if (deps.refs.fileInput.files.length === 0) {
                        deps.refs.fileLabel.textContent = 'Attach files';
                    } else if (deps.refs.fileInput.files.length === 1) {
                        deps.refs.fileLabel.textContent = deps.refs.fileInput.files[0].name;
                    } else {
                        deps.refs.fileLabel.textContent = `${deps.refs.fileInput.files.length} files selected`;
                    }
                    refreshAttachChips();
                });
            }

            if (deps.refs.composerInputRow) {
                deps.refs.composerInputRow.addEventListener('dragenter', (event) => {
                    if (!composerDropHasFiles(event)) return;
                    event.preventDefault();
                    composerDragDepth += 1;
                    setComposerDropActive(true);
                });
                deps.refs.composerInputRow.addEventListener('dragover', (event) => {
                    if (!composerDropHasFiles(event)) return;
                    event.preventDefault();
                    event.dataTransfer.dropEffect = 'copy';
                    setComposerDropActive(true);
                });
                deps.refs.composerInputRow.addEventListener('dragleave', (event) => {
                    if (!composerDropHasFiles(event)) return;
                    event.preventDefault();
                    composerDragDepth = Math.max(0, composerDragDepth - 1);
                    if (composerDragDepth === 0) setComposerDropActive(false);
                });
                deps.refs.composerInputRow.addEventListener('drop', (event) => {
                    if (!composerDropHasFiles(event)) return;
                    event.preventDefault();
                    event.stopPropagation();
                    composerDragDepth = 0;
                    setComposerDropActive(false);
                    const droppedFiles = Array.from(event.dataTransfer.files || []);
                    if (!droppedFiles.length) return;
                    const attached = syncLocalFileSelection(droppedFiles, { append: true });
                    if (!attached) {
                        deps.helpers.showToast?.('error', 'Drag-and-drop is not available in this browser.', 3500);
                        return;
                    }
                    deps.helpers.showToast?.('success', droppedFiles.length === 1 ? `Attached ${droppedFiles[0].name}` : `Attached ${droppedFiles.length} files`, 2200);
                    if (deps.refs.goalInput) deps.refs.goalInput.focus();
                });
            }

            if (deps.refs.onedriveModeLocal) {
                deps.refs.onedriveModeLocal.addEventListener('change', () => {
                    if (deps.refs.onedriveModeLocal.checked) applyOneDriveMode('local');
                });
            }
            if (deps.refs.onedriveModeGraph) {
                deps.refs.onedriveModeGraph.addEventListener('change', () => {
                    if (deps.refs.onedriveModeGraph.checked) applyOneDriveMode('graph');
                });
            }
            if (deps.refs.onedriveDetectBtn) {
                deps.refs.onedriveDetectBtn.addEventListener('click', async () => {
                    deps.refs.onedriveDetectBtn.disabled = true;
                    try {
                        const response = await deps.authFetch('/api/integrations/microsoft/detect-local');
                        const data = await response.json();
                        if (data.path) {
                            if (deps.refs.onedriveLocalPath) deps.refs.onedriveLocalPath.value = data.path;
                            if (deps.refs.onedriveLocalStatus) {
                                deps.refs.onedriveLocalStatus.textContent = '✅ Detected: ' + data.path;
                                deps.refs.onedriveLocalStatus.className = 'settings-note ok';
                            }
                        } else if (deps.refs.onedriveLocalStatus) {
                            deps.refs.onedriveLocalStatus.textContent = 'Could not detect a local OneDrive folder. Enter the path manually.';
                            deps.refs.onedriveLocalStatus.className = 'settings-note';
                        }
                    } catch {
                        if (deps.refs.onedriveLocalStatus) deps.refs.onedriveLocalStatus.textContent = 'Detection failed.';
                    }
                    deps.refs.onedriveDetectBtn.disabled = false;
                });
            }

            if (deps.refs.attachGoogleDrive) {
                deps.refs.attachGoogleDrive.addEventListener('click', () => {
                    closeAttachPopup();
                    openCloudBrowser('google_drive', 'Google Drive');
                });
            }
            if (deps.refs.attachOneDrive) {
                deps.refs.attachOneDrive.addEventListener('click', () => {
                    closeAttachPopup();
                    const provider = oneDriveMode === 'local' ? 'onedrive_local' : 'onedrive';
                    openCloudBrowser(provider, 'OneDrive');
                });
            }
            if (deps.refs.cloudClose) {
                deps.refs.cloudClose.addEventListener('click', () => {
                    closeCloudBrowser();
                });
            }
            if (deps.refs.cloudOverlay) {
                deps.refs.cloudOverlay.addEventListener('click', (event) => {
                    if (event.target === deps.refs.cloudOverlay) closeCloudBrowser();
                });
            }
            if (deps.refs.cloudBack) {
                deps.refs.cloudBack.addEventListener('click', () => {
                    if (cloudNavStack.length === 0) return;
                    const previous = cloudNavStack.pop();
                    cloudBrowse(previous.id === 'root' ? previous.id : previous.id, previous.name);
                    if (cloudNavStack.length === 0) {
                        cloudUpdateBreadcrumb('Root');
                    } else {
                        cloudUpdateBreadcrumb(previous.name);
                    }
                });
            }
            if (deps.refs.cloudAttachBtn) {
                deps.refs.cloudAttachBtn.addEventListener('click', () => {
                    if (cloudSelectMode === 'folder') {
                        if (cloudFolderSelectCallback && cloudCurrentFolder) {
                            cloudFolderSelectCallback({ ...cloudCurrentFolder, provider: cloudProvider });
                        }
                        closeCloudBrowser();
                        return;
                    }
                    if (cloudSelected.size === 0) return;
                    const files = Array.from(cloudSelected.values());
                    for (const file of files) {
                        cloudAttachedFiles.push({
                            provider: cloudProvider,
                            id: file.id,
                            name: file.name,
                        });
                    }
                    closeCloudBrowser();
                    refreshAttachChips();
                });
            }
        }

        return {
            bindUi,
            applyOneDriveMode,
            cloudUpdateStatus,
            openCloudBrowser,
            refreshAttachChips,
            buildFolderAttachmentContext,
            captureStructuralContextSnapshot,
            storeLastSentContextSnapshot,
            cloudAttachedFiles,
            getOneDriveMode: () => oneDriveMode,
        };
    };
})();