/**
 * Deal Flow — Pipeline Kanban JavaScript
 *
 * Extracted from pipeline.html.twig inline <script> blocks.
 * Requires window.DealFlowConfig to be set by the Twig template with:
 *   - pipelineVelocity: Velocity data object keyed by period (7, 14, 30)
 *   - pipelineUrl:      Base pipeline URL for search/navigation
 *
 * Also requires window.DealFlow (from _scripts.html.twig) and mQuery (Mautic jQuery).
 */
(function () {
    'use strict';

    var config = window.DealFlowConfig || {};
    var velocityData = config.pipelineVelocity || {};

    // Velocity pill switching
    document.querySelectorAll('[data-velocity-period]').forEach(function (pill) {
        pill.addEventListener('click', function () {
            document.querySelectorAll('[data-velocity-period]').forEach(function (p) { p.classList.remove('is-active'); });
            pill.classList.add('is-active');
            var d = velocityData[pill.getAttribute('data-velocity-period')];
            if (!d) return;
            var fwdEl = document.querySelector('[data-velocity-val="fwd"]');
            var wonEl = document.querySelector('[data-velocity-val="won"]');
            var lostEl = document.querySelector('[data-velocity-val="lost"]');
            if (fwdEl) fwdEl.textContent = d.fwd;
            if (wonEl) wonEl.textContent = d.won;
            if (lostEl) lostEl.textContent = d.lost;
            var fwdSeg = document.querySelector('[data-velocity-seg="fwd"]');
            var wonSeg = document.querySelector('[data-velocity-seg="won"]');
            var lostSeg = document.querySelector('[data-velocity-seg="lost"]');
            if (fwdSeg) fwdSeg.style.width = d.fwdPct;
            if (wonSeg) wonSeg.style.width = d.wonPct;
            if (lostSeg) lostSeg.style.width = d.lostPct;
        });
    });

    // Live search
    var searchForm = document.querySelector('[data-dealflow-live-search]');
    var searchInput = searchForm ? searchForm.querySelector('[data-dealflow-live-search-input]') : null;
    var searchTimer = null;
    var lastSearchValue = searchInput ? searchInput.value.trim() : '';

    if (searchForm && searchInput) {
        var submitSearch = function () {
            var nextSearchValue = searchInput.value.trim();

            if (nextSearchValue === lastSearchValue) {
                return;
            }

            lastSearchValue = nextSearchValue;

            var nextUrl = new URL(searchForm.getAttribute('action') || window.location.pathname, window.location.origin);

            if (nextSearchValue !== '') {
                nextUrl.searchParams.set('search', nextSearchValue);
            }

            if (window.Mautic && typeof window.Mautic.loadContent === 'function') {
                window.Mautic.loadContent(nextUrl.pathname + nextUrl.search);
            } else {
                window.location.assign(nextUrl.pathname + nextUrl.search);
            }
        };

        searchInput.addEventListener('input', function () {
            window.clearTimeout(searchTimer);
            searchTimer = window.setTimeout(submitSearch, 800);
        });

        searchInput.addEventListener('keydown', function (event) {
            if (event.key !== 'Enter') {
                return;
            }

            event.preventDefault();
            window.clearTimeout(searchTimer);
            submitSearch();
        });

        searchForm.addEventListener('submit', function (event) {
            event.preventDefault();
            window.clearTimeout(searchTimer);
            submitSearch();
        });
    }

    // Drag and drop
    var board = document.querySelector('[data-dealflow-board]');
    if (!board) {
        return;
    }

    var draggedCard = null;
    var dragPlaceholder = null;
    var dragPreview = null;
    var dragPointerOffsetX = 0;
    var dragPointerOffsetY = 0;
    var suppressNextCardClick = false;

    var rollbackDragDrop = function (card, sourceStage, targetStage, originalStageId) {
        window.DealFlow.rollbackDragDrop(card, sourceStage, targetStage, originalStageId, updateStageCounts);
    };

    var showToast = function (message) {
        window.DealFlow.showToast(message);
    };

    var clearDropTargets = function () {
        board.querySelectorAll('[data-stage-dropzone]').forEach(function (dropzone) {
            dropzone.classList.remove('is-drop-target');
            var emptyState = dropzone.querySelector('.dfp-stage__empty');
            if (emptyState) {
                emptyState.classList.remove('is-hidden-during-drag');
            }
        });
    };

    var removeDragArtifacts = function () {
        if (dragPlaceholder && dragPlaceholder.parentNode) {
            dragPlaceholder.parentNode.removeChild(dragPlaceholder);
        }

        if (dragPreview && dragPreview.parentNode) {
            dragPreview.parentNode.removeChild(dragPreview);
        }

        dragPlaceholder = null;
        dragPreview = null;
    };

    var positionDragPreview = function (clientX, clientY) {
        if (!dragPreview) {
            return;
        }

        dragPreview.style.left = Math.round(clientX - dragPointerOffsetX) + 'px';
        dragPreview.style.top = Math.round(clientY - dragPointerOffsetY) + 'px';
    };

    var movePlaceholderIntoDropzone = function (dropzone) {
        if (!dragPlaceholder || !dropzone) {
            return;
        }

        var emptyState = dropzone.querySelector('.dfp-stage__empty');
        if (emptyState) {
            dropzone.insertBefore(dragPlaceholder, emptyState);
        } else if (dragPlaceholder.parentNode !== dropzone) {
            dropzone.appendChild(dragPlaceholder);
        }
    };

    var formatCompactAmount = function (amount) {
        var abs = Math.abs(amount);
        var prefix = '$';
        var result;
        if (abs >= 1000000) {
            var scaledM = abs / 1000000;
            result = prefix + (scaledM === Math.floor(scaledM) ? scaledM.toFixed(0) : scaledM.toFixed(1)) + 'mm';
        } else if (abs >= 1000) {
            var scaledK = abs / 1000;
            result = prefix + (scaledK === Math.floor(scaledK) ? scaledK.toFixed(0) : scaledK.toFixed(1)) + 'k';
        } else if (abs === Math.floor(abs)) {
            result = prefix + abs.toFixed(0);
        } else {
            result = prefix + abs.toFixed(2);
        }
        return amount < 0 ? '-' + result : result;
    };

    var updateStageCounts = function (stageElement, delta, amountDelta) {
        if (!stageElement) {
            return;
        }

        if (delta) {
            var countElement = stageElement.querySelector('[data-stage-count]');
            var summaryElement = stageElement.querySelector('[data-stage-summary-count]');

            if (countElement && summaryElement) {
                var nextCount = Math.max(0, parseInt(countElement.textContent, 10) + delta);
                countElement.textContent = String(nextCount);
                summaryElement.textContent = nextCount + ' deal' + (nextCount === 1 ? '' : 's');
            }
        }

        if (amountDelta) {
            var totalElement = stageElement.querySelector('[data-stage-total]');
            if (totalElement) {
                var currentTotal = parseFloat(totalElement.getAttribute('data-stage-total')) || 0;
                var nextTotal = Math.max(0, currentTotal + amountDelta);
                totalElement.setAttribute('data-stage-total', String(nextTotal));
                totalElement.textContent = nextTotal === 0 ? '$0' : formatCompactAmount(nextTotal);
            }
        }
    };

    board.querySelectorAll('[data-deal-card]').forEach(function (card) {
        var openCard = function () {
            var titleLink = card.querySelector('.dfp-card__title');
            if (titleLink) {
                titleLink.click();
            }
        };

        card.addEventListener('dragstart', function (event) {
            draggedCard = card;
            suppressNextCardClick = true;
            card.classList.add('is-dragging-source');

            var rect = card.getBoundingClientRect();
            dragPointerOffsetX = event.clientX - rect.left;
            dragPointerOffsetY = event.clientY - rect.top;

            dragPlaceholder = document.createElement('div');
            dragPlaceholder.className = 'dfp-card__placeholder';
            dragPlaceholder.style.height = card.offsetHeight + 'px';
            card.parentNode.insertBefore(dragPlaceholder, card.nextSibling);

            dragPreview = card.cloneNode(true);
            dragPreview.classList.add('dfp-card--preview');
            dragPreview.style.position = 'fixed';
            dragPreview.style.width = card.offsetWidth + 'px';
            document.body.appendChild(dragPreview);
            positionDragPreview(event.clientX, event.clientY);

            window.setTimeout(function () {
                card.style.display = 'none';
            }, 0);

            if (event.dataTransfer) {
                event.dataTransfer.effectAllowed = 'move';
                event.dataTransfer.setData('text/plain', card.getAttribute('data-deal-id') || '');
                var dragPixel = document.createElement('canvas');
                dragPixel.width = 1;
                dragPixel.height = 1;
                event.dataTransfer.setDragImage(dragPixel, 0, 0);
            }
        });

        card.addEventListener('dragend', function () {
            card.classList.remove('is-dragging-source');
            card.style.display = '';
            draggedCard = null;
            clearDropTargets();
            removeDragArtifacts();
            window.setTimeout(function () {
                suppressNextCardClick = false;
            }, 0);
        });

        card.addEventListener('click', function (event) {
            if (suppressNextCardClick || draggedCard) {
                return;
            }

            if (event.target.closest('a, button, input, select, textarea, label, form')) {
                return;
            }

            openCard();
        });

        card.addEventListener('keydown', function (event) {
            if (suppressNextCardClick || draggedCard) {
                return;
            }

            if (event.target.closest('a, button, input, select, textarea, label, form')) {
                return;
            }

            if (event.key === 'Enter' || event.key === ' ') {
                event.preventDefault();
                openCard();
            }
        });
    });

    board.querySelectorAll('[data-stage-dropzone]').forEach(function (dropzone) {
        dropzone.addEventListener('dragover', function (event) {
            if (!draggedCard) {
                return;
            }

            event.preventDefault();
            positionDragPreview(event.clientX, event.clientY);
            clearDropTargets();
            dropzone.classList.add('is-drop-target');
            movePlaceholderIntoDropzone(dropzone);

            var emptyState = dropzone.querySelector('.dfp-stage__empty');
            if (emptyState) {
                emptyState.classList.add('is-hidden-during-drag');
            }

            if (event.dataTransfer) {
                event.dataTransfer.dropEffect = 'move';
            }
        });

        dropzone.addEventListener('drop', function (event) {
            if (!draggedCard) {
                return;
            }

            event.preventDefault();
            clearDropTargets();

            var targetStageId = dropzone.getAttribute('data-stage-dropzone');
            var currentStageId = draggedCard.getAttribute('data-current-stage-id');

            if (!targetStageId || targetStageId === currentStageId) {
                clearDropTargets();
                removeDragArtifacts();
                return;
            }

            var form = draggedCard.querySelector('[data-stage-form]');
            var select = draggedCard.querySelector('[data-stage-select]');

            if (!form || !select) {
                console.error('DealFlow: stage form not found on card', draggedCard);
                showToast('Could not move deal \u2014 form not found. Try refreshing.');
                clearDropTargets();
                removeDragArtifacts();
                return;
            }

            var formAction = form.getAttribute('action');
            select.value = targetStageId;
            var formData = new FormData(form);
            var boardScrollLeft = board.scrollLeft;

            var sourceStage = draggedCard.closest('.dfp-stage');
            var targetStage = dropzone.closest('.dfp-stage');
            var targetEmptyState = dropzone.querySelector('.dfp-stage__empty');

            if (targetEmptyState && targetEmptyState.parentNode) {
                targetEmptyState.parentNode.removeChild(targetEmptyState);
            }

            draggedCard.style.display = '';
            draggedCard.classList.remove('is-dragging-source');
            movePlaceholderIntoDropzone(dropzone);
            if (dragPlaceholder && dragPlaceholder.parentNode) {
                dragPlaceholder.parentNode.replaceChild(draggedCard, dragPlaceholder);
            } else {
                dropzone.appendChild(draggedCard);
            }
            draggedCard.scrollIntoView({block: 'nearest', inline: 'nearest'});

            var dealAmount = parseFloat(draggedCard.getAttribute('data-deal-amount')) || 0;
            updateStageCounts(sourceStage, -1, -dealAmount);
            updateStageCounts(targetStage, 1, dealAmount);
            draggedCard.setAttribute('data-current-stage-id', targetStageId);
            clearDropTargets();
            removeDragArtifacts();

            var xhr = new XMLHttpRequest();
            xhr.open('POST', formAction);
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.setRequestHeader('X-CSRF-Token', mauticAjaxCsrf);

            var movedCard = draggedCard;
            movedCard.classList.add('is-submitting');

            xhr.onload = function () {
                movedCard.classList.remove('is-submitting');
                var ok = xhr.status >= 200 && xhr.status < 300;
                if (ok) {
                    try {
                        var resp = JSON.parse(xhr.responseText);
                        if (resp.success === false || (resp.flashes && !resp.success)) {
                            ok = false;
                            rollbackDragDrop(movedCard, sourceStage, targetStage, currentStageId);
                            showToast('Failed: ' + (resp.error || 'Server rejected the request. Please refresh and try again.'));
                            return;
                        }
                    } catch (e) { /* non-JSON response, treat as success if 2xx */ }
                    movedCard.setAttribute('data-current-stage-id', targetStageId);
                    board.scrollLeft = boardScrollLeft;

                    var targetStageType = targetStage.classList.contains('dfp-stage--won') ? 'won'
                        : targetStage.classList.contains('dfp-stage--lost') ? 'lost'
                        : 'fwd';

                    var velEl = document.querySelector('[data-velocity-val="' + targetStageType + '"]');
                    if (velEl) {
                        velEl.textContent = String(parseInt(velEl.textContent, 10) + 1);
                    }

                    for (var period in velocityData) {
                        if (velocityData.hasOwnProperty(period)) {
                            velocityData[period][targetStageType] += 1;
                            var t = velocityData[period].fwd + velocityData[period].won + velocityData[period].lost;
                            velocityData[period].fwdPct = t > 0 ? Math.round(velocityData[period].fwd / t * 100) + '%' : '0%';
                            velocityData[period].wonPct = t > 0 ? Math.round(velocityData[period].won / t * 100) + '%' : '0%';
                            velocityData[period].lostPct = t > 0 ? Math.round(velocityData[period].lost / t * 100) + '%' : '0%';
                        }
                    }

                    var activePill = document.querySelector('[data-velocity-period].is-active');
                    var activePeriod = activePill ? activePill.getAttribute('data-velocity-period') : '14';
                    var activeData = velocityData[activePeriod];
                    if (activeData) {
                        var fwdSeg = document.querySelector('[data-velocity-seg="fwd"]');
                        var wonSeg = document.querySelector('[data-velocity-seg="won"]');
                        var lostSeg = document.querySelector('[data-velocity-seg="lost"]');
                        if (fwdSeg) fwdSeg.style.width = activeData.fwdPct;
                        if (wonSeg) wonSeg.style.width = activeData.wonPct;
                        if (lostSeg) lostSeg.style.width = activeData.lostPct;
                    }
                } else {
                    rollbackDragDrop(movedCard, sourceStage, targetStage, currentStageId);
                    showToast('Failed to move deal (HTTP ' + xhr.status + '). Please try again.');
                }
            };

            xhr.onerror = function () {
                movedCard.classList.remove('is-submitting');
                rollbackDragDrop(movedCard, sourceStage, targetStage, currentStageId);
                showToast('Network error. Please try again.');
            };

            xhr.send(formData);
        });
    });
})();
