/**
 * Deal Flow — Deal View Page JavaScript
 *
 * Extracted from view.html.twig inline <script> blocks.
 * Requires window.DealFlowConfig to be set by the Twig template with:
 *   - csrfUrl:           URL for CSRF token refresh endpoint
 *   - dealId:            Current deal ID
 *   - noteAddUrl:        URL for adding notes
 *   - noteEditUrlTpl:    URL template for editing notes (with 999999 placeholder)
 *   - noteDeleteUrlTpl:  URL template for deleting notes (with 999999 placeholder)
 *   - taskEditUrlTpl:    URL template for editing tasks (with 999999 placeholder)
 *   - taskDeleteUrlTpl:  URL template for deleting tasks (with 999999 placeholder)
 *   - taskUncompleteUrlTpl: URL template for uncompleting tasks (with 999999 placeholder)
 *   - contactDetachUrlTpl:  URL template for detaching contacts (with 999999 placeholder)
 *   - inlineEditUrl:     URL for inline field editing
 *   - moveStageUrlTpl:   URL template for moving stages (with __ID__ placeholder)
 *   - moveStageCsrf:     CSRF token for stage moves
 *   - companySearchUrl:  URL for company search
 *   - noteAddCsrf:       CSRF token for adding notes
 *   - apiDealUrlTpl:     URL template for deal API (with __ID__ placeholder)
 *
 * Also requires window.DealFlow (from _scripts.html.twig) and mQuery (Mautic jQuery).
 */
(function () {
    'use strict';

    var config = window.DealFlowConfig || {};

    /* ---- DealView namespace ---- */
    var DealView = window.DealView = {};

    /* ---- CSRF-resilient XHR wrapper ---- */

    var _csrfRefreshing = null;

    function refreshCsrfToken() {
        if (_csrfRefreshing) return _csrfRefreshing;
        _csrfRefreshing = new Promise(function(resolve, reject) {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', config.csrfUrl);
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.onload = function() {
                _csrfRefreshing = null;
                if (xhr.status === 200) {
                    try {
                        var resp = JSON.parse(xhr.responseText);
                        if (resp.token) {
                            mauticAjaxCsrf = resp.token;
                            resolve(resp.token);
                            return;
                        }
                    } catch(e) {}
                }
                reject(new Error('Token refresh failed'));
            };
            xhr.onerror = function() { _csrfRefreshing = null; reject(new Error('Network error')); };
            xhr.send();
        });
        return _csrfRefreshing;
    }

    function isCsrfError(xhr) {
        if (xhr.status === 200) {
            try {
                var r = JSON.parse(xhr.responseText);
                if (r.flashes && typeof r.success === 'undefined') return true;
            } catch(e) {}
        }
        if (xhr.status === 403) {
            try {
                var r403 = JSON.parse(xhr.responseText);
                if (r403.error && r403.error.toLowerCase().indexOf('csrf') !== -1) return true;
            } catch(e) {}
        }
        return false;
    }

    function dealflowFetch(method, url, body, opts) {
        opts = opts || {};
        var headers = opts.headers || {};

        function doRequest(isRetry) {
            var xhr = new XMLHttpRequest();
            xhr.open(method, url);
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.setRequestHeader('X-CSRF-Token', mauticAjaxCsrf);
            for (var k in headers) {
                if (headers.hasOwnProperty(k)) xhr.setRequestHeader(k, headers[k]);
            }
            xhr.onload = function() {
                if (isCsrfError(xhr) && !isRetry) {
                    refreshCsrfToken().then(function() {
                        doRequest(true);
                    }).catch(function() {
                        if (opts.onError) opts.onError({status: xhr.status, response: xhr.responseText, isCsrf: true});
                    });
                    return;
                }
                if (xhr.status >= 200 && xhr.status < 300) {
                    if (opts.onSuccess) opts.onSuccess(xhr);
                } else {
                    if (opts.onError) opts.onError({status: xhr.status, response: xhr.responseText, isCsrf: false});
                }
            };
            xhr.onerror = function() {
                if (opts.onError) opts.onError({status: 0, response: null, isCsrf: false});
            };
            xhr.send(body || null);
        }

        doRequest(false);
    }

    window.dealflowFetch = dealflowFetch;
    window.refreshCsrfToken = refreshCsrfToken;
    window._csrfRefreshing = _csrfRefreshing;

    /* ---- Contact Lookup ---- */
    Mautic.updateDealFlowContactLookupListFilter = function (field, item) {
        if (item && item.id) {
            mQuery('#dealflow_associate_contact_id').val(item.id);
            mQuery('#' + field).val(item.value || item.name || '');
        }
    };

    Mautic.activateDealFlowContactLookupField = function () {
        var lookupElementId = 'dealflow_associate_contact_display';
        var fieldEl = mQuery('#' + lookupElementId);
        if (!fieldEl.length) return;
        var action = fieldEl.attr('data-chosen-lookup');
        var options = { limit: 20, searchKey: 'lead.lead' };
        Mautic.activateFieldTypeahead(lookupElementId, 'undefined', options, action);
        fieldEl.off('change.dealflow').on('change.dealflow', function (event) {
            if (event.target.value === '') {
                mQuery('#dealflow_associate_contact_id').val('');
            }
        });
    };
    Mautic.activateDealFlowContactLookupField();

    /* ---- WYSIWYG helpers ---- */
    function initCkEditor(textarea, basicToolbar) {
        if (!textarea || typeof Mautic.InitCkEditor !== 'function') return;
        if (!basicToolbar) {
            basicToolbar = ['bold', 'italic', 'underline', '|', 'numberedList', 'bulletedList', '|', 'link', 'removeFormat'];
        }
        var opts = (typeof Mautic.GetCkEditorConfigOptions === 'function')
            ? Mautic.GetCkEditorConfigOptions(basicToolbar, null, mQuery(textarea))
            : { toolbar: basicToolbar };
        Mautic.InitCkEditor(mQuery(textarea), opts);
    }

    function getCkEditorContent(textarea) {
        if (!textarea) return '';
        if (typeof ckEditors !== 'undefined' && ckEditors.has(textarea)) {
            return ckEditors.get(textarea).getData();
        }
        if (window.CKEDITOR && window.CKEDITOR.instances && window.CKEDITOR.instances[textarea.id]) {
            return window.CKEDITOR.instances[textarea.id].getData();
        }
        return textarea.value || '';
    }

    function setCkEditorContent(textarea, content) {
        if (!textarea) return;
        if (typeof ckEditors !== 'undefined' && ckEditors.has(textarea)) {
            ckEditors.get(textarea).setData(content);
        } else {
            textarea.value = content;
        }
    }

    function destroyCkEditor(textarea) {
        if (!textarea) return;
        if (typeof ckEditors !== 'undefined' && ckEditors.has(textarea)) {
            ckEditors.get(textarea).destroy();
            ckEditors.delete(textarea);
        }
    }

    /* ---- WYSIWYG for Add Note modal ---- */
    mQuery('#dealflowAddNote').on('shown.bs.modal', function () {
        var textarea = document.getElementById('dealflow_note_body');
        if (textarea && !textarea._editorInit) {
            textarea._editorInit = true;
            initCkEditor(textarea);
        }
    });

    /* ---- Add Note: AJAX submit ---- */
    mQuery('#dealflowAddNoteSubmit').on('click', function () {
        var textarea = document.getElementById('dealflow_note_body');
        var body = getCkEditorContent(textarea);
        mQuery('#dealflowAddNoteError').hide();
        if (!body || !body.trim()) {
            mQuery('#dealflowAddNoteError').text('Note body cannot be empty.').show();
            return;
        }
        var data = new FormData();
        data.append('body', body);
        data.append('_token', config.noteAddCsrf);
        dealflowFetch('POST', config.noteAddUrl, data, {
            onSuccess: function(xhr) {
                if (xhr.status === 200) {
                    try {
                        var resp = JSON.parse(xhr.responseText);
                        if (resp.success) {
                            mQuery('#dealflowAddNote').modal('hide');
                            window.location.reload();
                        } else {
                            mQuery('#dealflowAddNoteError').text(resp.error || 'Failed to save note.').show();
                        }
                    } catch (e) {
                        mQuery('#dealflowAddNote').modal('hide');
                        window.location.reload();
                    }
                } else {
                    try {
                        var errResp = JSON.parse(xhr.responseText);
                        mQuery('#dealflowAddNoteError').text(errResp.error || 'Failed to save note.').show();
                    } catch (e) {
                        mQuery('#dealflowAddNoteError').text('Failed to save note.').show();
                    }
                }
            },
            onError: function() { mQuery('#dealflowAddNoteError').text('Failed to save note.').show(); }
        });
    });

    /* Clear Add Note modal on hide */
    mQuery('#dealflowAddNote').on('hidden.bs.modal', function () {
        mQuery('#dealflowAddNoteError').hide();
        var textarea = document.getElementById('dealflow_note_body');
        setCkEditorContent(textarea, '');
    });

    /* ---- WYSIWYG for Edit Note modal ---- */
    mQuery('#dealflowEditNote').on('shown.bs.modal', function () {
        var textarea = document.getElementById('editNoteBody');
        destroyCkEditor(textarea);
        initCkEditor(textarea);
    });

    /* ---- Open Edit Note modal ---- */
    DealView.openEditNote = function (noteId, btn) {
        document.getElementById('editNoteId').value = noteId;
        var body = btn ? btn.getAttribute('data-note-body') : '';
        var textarea = document.getElementById('editNoteBody');
        if (textarea) { textarea.value = body || ''; }
        mQuery('#dealflowEditNoteError').hide();
        var deleteBtn = document.getElementById('deleteNoteBtn');
        if (deleteBtn) { deleteBtn.dataset.confirming = ''; deleteBtn.textContent = 'Delete Note'; }
        mQuery('#dealflowEditNote').modal('show');
    };

    /* ---- Edit Note: AJAX submit ---- */
    mQuery('#dealflowEditNoteSubmit').on('click', function () {
        var noteId = document.getElementById('editNoteId').value;
        var textarea = document.getElementById('editNoteBody');
        var body = getCkEditorContent(textarea);
        mQuery('#dealflowEditNoteError').hide();
        if (!body || !body.trim()) {
            mQuery('#dealflowEditNoteError').text('Note body cannot be empty.').show();
            return;
        }
        var editUrl = config.noteEditUrlTpl.replace('999999', noteId);
        var data = new FormData();
        data.append('body', body);
        dealflowFetch('POST', editUrl, data, {
            onSuccess: function(xhr) {
                if (xhr.status === 200) {
                    try {
                        var resp = JSON.parse(xhr.responseText);
                        if (resp.success) {
                            mQuery('#dealflowEditNote').modal('hide');
                            window.location.reload();
                        } else {
                            mQuery('#dealflowEditNoteError').text(resp.error || 'Failed to save note.').show();
                        }
                    } catch (e) {
                        mQuery('#dealflowEditNote').modal('hide');
                        window.location.reload();
                    }
                } else {
                    try {
                        var errResp = JSON.parse(xhr.responseText);
                        mQuery('#dealflowEditNoteError').text(errResp.error || 'Failed to save note.').show();
                    } catch (e) {
                        mQuery('#dealflowEditNoteError').text('Failed to save note.').show();
                    }
                }
            },
            onError: function() { mQuery('#dealflowEditNoteError').text('Failed to save note.').show(); }
        });
    });

    /* ---- Delete Note ---- */
    mQuery('#deleteNoteBtn').on('click', function () {
        var btn = this;
        if (btn.dataset.confirming === 'true') {
            var noteId = document.getElementById('editNoteId').value;
            var deleteUrl = config.noteDeleteUrlTpl.replace('999999', noteId);
            dealflowFetch('POST', deleteUrl, null, {
                onSuccess: function(xhr) {
                    if (xhr.status === 200) {
                        mQuery('#dealflowEditNote').modal('hide');
                        window.location.reload();
                    }
                }
            });
        } else {
            btn.dataset.confirming = 'true';
            btn.textContent = 'Confirm Delete?';
            setTimeout(function () { btn.dataset.confirming = ''; btn.textContent = 'Delete Note'; }, 3000);
        }
    });

    /* Reset delete button state when Edit Note modal is hidden */
    mQuery('#dealflowEditNote').on('hidden.bs.modal', function () {
        var btn = document.getElementById('deleteNoteBtn');
        if (btn) { btn.dataset.confirming = ''; btn.textContent = 'Delete Note'; }
        mQuery('#dealflowEditNoteError').hide();
    });

    /* ---- WYSIWYG for Add Task modal ---- */
    mQuery('#dealflowAddTask').on('shown.bs.modal', function () {
        var textarea = document.getElementById('dealflow_task_description');
        if (textarea && !textarea._editorInit) {
            textarea._editorInit = true;
            initCkEditor(textarea);
        }
    });

    /* ---- WYSIWYG for Edit Task modal ---- */
    mQuery('#dealflowEditTask').on('shown.bs.modal', function () {
        var textarea = document.getElementById('editTaskDescription');
        destroyCkEditor(textarea);
        initCkEditor(textarea);
    });

    /* ---- Associate Contact modal typeahead ---- */
    mQuery('#dealflowAssociateContact').on('shown.bs.modal', function () {
        Mautic.activateDealFlowContactLookupField();
    });

    /* ---- Task Edit ---- */
    DealView.openEditTask = function(taskId, title, priority, dueAt, ownerId, description, status) {
        document.getElementById('editTaskId').value = taskId;
        document.getElementById('editTaskTitle').value = title;
        document.getElementById('editTaskPriority').value = priority;
        document.getElementById('editTaskDueAt').value = dueAt;
        document.getElementById('editTaskOwner').value = ownerId;
        document.getElementById('editTaskDescription').value = description;
        document.getElementById('editTaskStatus').value = status;
        mQuery('#dealflowEditTask').modal('show');
    };

    DealView.saveTask = function() {
        var taskId = document.getElementById('editTaskId').value;
        var editTextarea = document.getElementById('editTaskDescription');
        var desc = getCkEditorContent(editTextarea);
        var data = new FormData();
        data.append('title', document.getElementById('editTaskTitle').value);
        data.append('priority', document.getElementById('editTaskPriority').value);
        data.append('due_at', document.getElementById('editTaskDueAt').value);
        data.append('owner_id', document.getElementById('editTaskOwner').value);
        data.append('description', desc);
        data.append('status', document.getElementById('editTaskStatus').value);

        var editUrl = config.taskEditUrlTpl.replace('999999', taskId);
        dealflowFetch('POST', editUrl, data, {
            onSuccess: function(xhr) {
                if (xhr.status === 200) {
                    try {
                        var resp = JSON.parse(xhr.responseText);
                        if (resp.success) {
                            mQuery('#dealflowEditTask').modal('hide');
                            window.location.reload();
                        } else {
                            alert(resp.error || 'Failed to save task.');
                        }
                    } catch (e) {
                        mQuery('#dealflowEditTask').modal('hide');
                        window.location.reload();
                    }
                } else {
                    alert('Failed to save task.');
                }
            },
            onError: function() { alert('Failed to save task.'); }
        });
    };

    /* ---- Task Delete ---- */
    DealView.deleteTask = function() {
        var btn = document.getElementById('deleteTaskBtn');
        if (btn.dataset.confirming === 'true') {
            var taskId = document.getElementById('editTaskId').value;
            dealflowFetch('POST', config.taskDeleteUrlTpl.replace('999999', taskId), null, {
                onSuccess: function(xhr) {
                    if (xhr.status === 200) {
                        mQuery('#dealflowEditTask').modal('hide');
                        window.location.reload();
                    }
                }
            });
        } else {
            btn.dataset.confirming = 'true';
            btn.textContent = 'Confirm Delete?';
            setTimeout(function() { btn.dataset.confirming = ''; btn.textContent = 'Delete Task'; }, 3000);
        }
    };

    /* Reset delete button state when modal is hidden */
    mQuery('#dealflowEditTask').on('hidden.bs.modal', function () {
        var btn = document.getElementById('deleteTaskBtn');
        if (btn) { btn.dataset.confirming = ''; btn.textContent = 'Delete Task'; }
    });

    /* ---- Task Uncomplete ---- */
    DealView.uncompleteTask = function(taskId) {
        var uncompleteUrl = config.taskUncompleteUrlTpl.replace('999999', String(taskId));
        dealflowFetch('POST', uncompleteUrl, null, {
            onSuccess: function(xhr) {
                if (xhr.status === 200) {
                    window.location.reload();
                }
            }
        });
    };

    /* ---- Contact Detach ---- */
    DealView._detachContactId = null;

    DealView.confirmDetachContact = function(contactId, contactName) {
        DealView._detachContactId = contactId;
        document.getElementById('detachContactName').textContent = contactName;
        mQuery('#dealflowDetachContact').modal('show');
    };

    DealView.detachContact = function() {
        var contactId = DealView._detachContactId;
        dealflowFetch('POST', config.contactDetachUrlTpl.replace('999999', String(contactId)), null, {
            onSuccess: function(xhr) {
                if (xhr.status === 200) {
                    mQuery('#dealflowDetachContact').modal('hide');
                    window.location.reload();
                }
            }
        });
    };

    /* ---- Inline Editing ---- */
    DealView.initInlineEditing = function() {
        document.querySelectorAll('.dv-inline-editable').forEach(function(el) {
            el.addEventListener('click', function() {
                if (el.classList.contains('dv-inline-editing')) return;

                var field = el.dataset.field;
                var type = el.dataset.type;
                var currentValue = el.dataset.value;
                var originalHtml = el.innerHTML;

                el.classList.add('dv-inline-editing');

                var input;
                if (type === 'select' && field === 'owner_id') {
                    input = document.createElement('select');
                    input.className = 'form-control input-sm';
                    var blankOpt = document.createElement('option');
                    blankOpt.value = '';
                    blankOpt.textContent = 'Unassigned';
                    input.appendChild(blankOpt);
                    var ownerSelect = document.getElementById('editTaskOwner');
                    if (ownerSelect) {
                        for (var i = 0; i < ownerSelect.options.length; i++) {
                            var opt = document.createElement('option');
                            opt.value = ownerSelect.options[i].value;
                            opt.textContent = ownerSelect.options[i].textContent;
                            if (opt.value === currentValue) opt.selected = true;
                            if (opt.value !== '') input.appendChild(opt);
                        }
                    }
                } else if (type === 'date') {
                    input = document.createElement('input');
                    input.type = 'date';
                    input.className = 'form-control input-sm';
                    input.value = currentValue;
                } else if (type === 'number') {
                    input = document.createElement('input');
                    input.type = 'number';
                    input.className = 'form-control input-sm';
                    input.value = currentValue;
                    if (field === 'confidence') { input.min = 0; input.max = 100; }
                } else if (type === 'company') {
                    var ctWrapper = document.createElement('span');
                    ctWrapper.style.cssText = 'position:relative;display:block;';
                    input = document.createElement('input');
                    input.type = 'text';
                    input.className = 'form-control input-sm';
                    input.placeholder = 'Type to search companies...';
                    input.value = '';
                    var ctSuggestions = document.createElement('span');
                    ctSuggestions.style.cssText = 'position:absolute;top:100%;left:0;right:0;background:#fff;border:1px solid var(--dv-border,#ddd);border-radius:0 0 4px 4px;max-height:160px;overflow-y:auto;z-index:1050;display:none;box-shadow:0 4px 8px rgba(0,0,0,.1);';
                    ctWrapper.appendChild(input);
                    ctWrapper.appendChild(ctSuggestions);
                    el.innerHTML = '';
                    el.appendChild(ctWrapper);
                    input.focus();

                    var ctDebounce;
                    var ctSaveCompany = function(companyId) {
                        dealflowFetch('POST', config.inlineEditUrl, 'field=company_id&value=' + encodeURIComponent(companyId), {
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                            onSuccess: function() { window.location.reload(); }
                        });
                    };

                    var ctBuildItems = function(companies) {
                        ctSuggestions.innerHTML = '';
                        var noneItem = document.createElement('span');
                        noneItem.textContent = '\u2014 None (clear) \u2014';
                        noneItem.style.cssText = 'display:block;padding:6px 8px;cursor:pointer;font-size:12px;color:var(--text-secondary,#666);font-style:italic;';
                        noneItem.addEventListener('mouseenter', function() { noneItem.style.background = '#f5f5f5'; });
                        noneItem.addEventListener('mouseleave', function() { noneItem.style.background = ''; });
                        noneItem.addEventListener('mousedown', function(e) { e.preventDefault(); ctSaveCompany(''); });
                        ctSuggestions.appendChild(noneItem);
                        if (companies.length > 0) {
                            var divider = document.createElement('span');
                            divider.style.cssText = 'display:block;border-top:1px solid var(--dv-border,#eee);margin:2px 0;';
                            ctSuggestions.appendChild(divider);
                        }
                        companies.forEach(function(c) {
                            var item = document.createElement('span');
                            item.textContent = c.name;
                            item.style.cssText = 'display:block;padding:6px 8px;cursor:pointer;font-size:12px;';
                            item.addEventListener('mouseenter', function() { item.style.background = '#f5f5f5'; });
                            item.addEventListener('mouseleave', function() { item.style.background = ''; });
                            item.addEventListener('mousedown', function(e) { e.preventDefault(); ctSaveCompany(c.id); });
                            ctSuggestions.appendChild(item);
                        });
                        ctSuggestions.style.display = 'block';
                    };

                    var ctFetch = function(q) {
                        var xhr2 = new XMLHttpRequest();
                        xhr2.open('GET', config.companySearchUrl + '?q=' + encodeURIComponent(q));
                        xhr2.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                        xhr2.onload = function() {
                            if (xhr2.status === 200) {
                                try {
                                    var companies = JSON.parse(xhr2.responseText);
                                    ctBuildItems(companies);
                                } catch (e) { /* ignore parse errors */ }
                            }
                        };
                        xhr2.send();
                    };

                    ctFetch('');

                    input.addEventListener('input', function() {
                        clearTimeout(ctDebounce);
                        ctDebounce = setTimeout(function() { ctFetch(input.value.trim()); }, 200);
                    });

                    input.addEventListener('blur', function() {
                        setTimeout(function() {
                            ctSuggestions.style.display = 'none';
                            el.innerHTML = originalHtml;
                            el.classList.remove('dv-inline-editing');
                        }, 250);
                    });

                    input.addEventListener('keydown', function(e) {
                        if (e.key === 'Escape') { el.innerHTML = originalHtml; el.classList.remove('dv-inline-editing'); }
                    });

                    return;
                } else {
                    input = document.createElement('input');
                    input.type = 'text';
                    input.className = 'form-control input-sm';
                    input.value = currentValue;
                }

                el.innerHTML = '';
                el.appendChild(input);
                input.focus();

                var save = function() {
                    var newValue = input.value;
                    dealflowFetch('POST', config.inlineEditUrl, 'field=' + encodeURIComponent(field) + '&value=' + encodeURIComponent(newValue), {
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        onSuccess: function(xhr) {
                            if (xhr.status === 200) {
                                try {
                                    var resp = JSON.parse(xhr.responseText);
                                    if (resp.success) {
                                        window.location.reload();
                                    } else {
                                        el.innerHTML = originalHtml;
                                        el.classList.remove('dv-inline-editing');
                                        if (window.DealFlow && window.DealFlow.showToast) {
                                            window.DealFlow.showToast(resp.error || 'Save failed', 'error');
                                        }
                                    }
                                } catch (e) {
                                    window.location.reload();
                                }
                            } else {
                                el.innerHTML = originalHtml;
                                el.classList.remove('dv-inline-editing');
                            }
                        },
                        onError: function() { el.innerHTML = originalHtml; el.classList.remove('dv-inline-editing'); }
                    });
                };

                input.addEventListener('blur', save);
                input.addEventListener('keydown', function(e) {
                    if (e.key === 'Enter') { e.preventDefault(); save(); }
                    if (e.key === 'Escape') { el.innerHTML = originalHtml; el.classList.remove('dv-inline-editing'); }
                });
            });
        });
    };

    /* Section collapse/expand */
    DealView.toggleCard = function (id) {
        var card = document.getElementById(id);
        if (!card) return;
        var body = card.querySelector('.dv-card-body');
        if (card.classList.contains('dv-collapsed')) {
            card.classList.remove('dv-collapsed');
            body.style.maxHeight = body.scrollHeight + 'px';
            setTimeout(function () { body.style.maxHeight = 'none'; }, 300);
        } else {
            body.style.maxHeight = body.scrollHeight + 'px';
            body.offsetHeight; // force reflow
            card.classList.add('dv-collapsed');
            body.style.maxHeight = '0';
        }
    };

    /* Init card bodies */
    document.querySelectorAll('.dv-card-body').forEach(function (body) {
        body.style.maxHeight = 'none';
    });

    /* Overdue tasks expand/collapse */
    var overdueAlert = document.getElementById('dvOverdueAlert');
    if (overdueAlert) {
        overdueAlert.addEventListener('click', function () {
            overdueAlert.classList.toggle('dv-expanded');
            document.getElementById('dvOverdueDetail').classList.toggle('dv-open');
        });
    }

    /* Show/hide completed tasks */
    var showCompletedBtn = document.getElementById('dvShowCompletedBtn');
    if (showCompletedBtn) {
        showCompletedBtn.addEventListener('click', function () {
            var wrapper = document.getElementById('dvCompletedTasks');
            wrapper.classList.toggle('dv-visible');
            var count = wrapper.querySelectorAll('.dv-task-item').length;
            showCompletedBtn.textContent = wrapper.classList.contains('dv-visible')
                ? 'Hide completed (' + count + ')'
                : 'Show completed (' + count + ')';
            var cardBody = wrapper.closest('.dv-card-body');
            if (cardBody) cardBody.style.maxHeight = 'none';
        });
    }

    /* Note truncation toggle */
    DealView.toggleNote = function (id) {
        var note = document.getElementById(id);
        var toggle = document.getElementById(id + 'Toggle');
        if (!note || !toggle) return;
        if (note.classList.contains('dv-truncated')) {
            note.classList.remove('dv-truncated');
            toggle.textContent = 'Show less';
        } else {
            note.classList.add('dv-truncated');
            toggle.textContent = 'Show more';
        }
        var cardBody = note.closest('.dv-card-body');
        if (cardBody) cardBody.style.maxHeight = 'none';
    };

    /* Show all activity */
    var showAllBtn = document.getElementById('dvShowAllActivity');
    if (showAllBtn) {
        showAllBtn.addEventListener('click', function () {
            document.querySelectorAll('[data-activity-hidden]').forEach(function (el) {
                el.style.display = '';
                el.removeAttribute('data-activity-hidden');
            });
            showAllBtn.style.display = 'none';
            var cardBody = showAllBtn.closest('.dv-card-body');
            if (cardBody) cardBody.style.maxHeight = 'none';
        });
    }

    /* Stage bar click -> AJAX move stage */
    function moveStage(stageId) {
        var formData = new FormData();
        formData.append('stage_id', stageId);
        formData.append('_token', config.moveStageCsrf);
        formData.append('return_url', window.location.pathname);

        dealflowFetch('POST', config.moveStageUrlTpl.replace('__ID__', String(config.dealId)), formData, {
            onSuccess: function(xhr) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    window.DealFlow.showToast('Stage updated.');
                    var stageEls = document.querySelectorAll('.dv-stage-bar .dv-stage');
                    var found = false;
                    stageEls.forEach(function (el) {
                        el.classList.remove('dv-completed', 'dv-current');
                        if (el.getAttribute('data-stage-id') == stageId) {
                            el.classList.add('dv-current');
                            found = true;
                        } else if (!found) {
                            el.classList.add('dv-completed');
                        }
                    });
                    var dropdown = document.getElementById('dvStageDropdown');
                    if (dropdown) dropdown.value = stageId;
                } else {
                    window.DealFlow.showToast('Failed to update stage.');
                }
            },
            onError: function() { window.DealFlow.showToast('Network error updating stage.'); }
        });
    }

    document.querySelectorAll('.dv-stage-bar .dv-stage').forEach(function (el) {
        el.addEventListener('click', function () {
            moveStage(el.getAttribute('data-stage-id'));
        });
    });

    var stageDropdown = document.getElementById('dvStageDropdown');
    if (stageDropdown) {
        stageDropdown.addEventListener('change', function () {
            moveStage(stageDropdown.value);
        });
    }

    /* Inline status change */
    document.querySelectorAll('[data-dealflow-inline-status]').forEach(function (select) {
        select.addEventListener('change', function () {
            var dealId = select.getAttribute('data-deal-id');
            var csrf = select.getAttribute('data-csrf');
            var status = select.value;
            var formData = new FormData();
            formData.append('deal[status]', status);
            formData.append('deal[_token]', csrf);

            dealflowFetch('PATCH', config.apiDealUrlTpl.replace('__ID__', dealId), formData, {
                onSuccess: function(xhr) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        window.DealFlow.showToast('Status updated.');
                    } else {
                        window.DealFlow.showToast('Failed to update status.');
                    }
                },
                onError: function() { window.DealFlow.showToast('Network error updating status.'); }
            });
        });
    });

    /* Delete confirmation: enable button only when user types "delete" */
    var deleteInput = document.getElementById('dvDeleteConfirmInput');
    var deleteBtn = document.getElementById('dvDeleteConfirmBtn');
    if (deleteInput && deleteBtn) {
        deleteInput.addEventListener('input', function () {
            deleteBtn.disabled = deleteInput.value.toLowerCase().trim() !== 'delete';
        });
    }

    /* Init inline editing */
    DealView.initInlineEditing();
})();
