{% extends '@MauticCore/Default/content.html.twig' %}

{% block headerTitle selectedPipeline.getName() %}

{% block actions %}
    {% if securityIsGranted('dealflow:deals:create') %}
        <a
            class="btn btn-primary"
            href="{{ path('mautic_dealflow_new', {'pipelineId': selectedPipeline.getId(), 'returnUrl': app.request.requestUri}) }}"
            data-toggle="ajaxmodal"
            data-target="#MauticSharedModal"
            data-header="New Deal"
            data-href="{{ path('mautic_dealflow_new', {'pipelineId': selectedPipeline.getId(), 'modal': 1, 'contentOnly': 1, 'returnUrl': app.request.requestUri}) }}"
        >
            <i class="ri-add-line"></i>
            New Deal
        </a>
    {% endif %}
{% endblock %}

{% block content %}
    {{ include('@DealFlow/_styles.html.twig') }}
    {{ include('@DealFlow/Deal/_nav.html.twig') }}

    {% if pipelines|length > 1 %}
        <form class="form-inline mb-lg" method="get">
            <div class="form-group">
                <label class="mr-sm" for="dealflow_pipeline_select">Pipeline</label>
                <select class="form-control" id="dealflow_pipeline_select" name="pipelineId" onchange="this.form.submit()">
                    {% for pipeline in pipelines %}
                        <option value="{{ pipeline.getId() }}" {% if selectedPipeline and pipeline.getId() == selectedPipeline.getId() %}selected{% endif %}>
                            {{ pipeline.getName() }}
                        </option>
                    {% endfor %}
                </select>
            </div>
        </form>
    {% endif %}

    {% set totalDeals = 0 %}
    {% set populatedStages = 0 %}
    {% set openStages = 0 %}

    {% for column in columns %}
        {% set totalDeals = totalDeals + column.deals|length %}
        {% if column.deals is not empty %}
            {% set populatedStages = populatedStages + 1 %}
        {% endif %}
        {% if column.stage.getStageType() == 'open' %}
            {% set openStages = openStages + 1 %}
        {% endif %}
    {% endfor %}

    <style>
        .dealflow-pipeline {
            color: var(--text-primary);
        }

        .dealflow-pipeline__hero {
            background: linear-gradient(135deg, var(--layer-01) 0%, var(--layer-02) 100%);
            border: 1px solid var(--border-subtle-01);
            border-radius: var(--border-radius-lg);
            margin-bottom: 24px;
            overflow: hidden;
            padding: 24px;
        }

        .dealflow-pipeline__hero-grid {
            align-items: end;
            display: grid;
            gap: 20px;
            grid-template-columns: minmax(0, 1.25fr) minmax(320px, .95fr);
        }

        .dealflow-pipeline__eyebrow {
            color: var(--text-secondary);
            font-size: 12px;
            font-weight: 700;
            letter-spacing: .08em;
            margin-bottom: 10px;
            text-transform: uppercase;
        }

        .dealflow-pipeline__title {
            color: var(--text-primary);
            font-size: 32px;
            font-weight: 700;
            letter-spacing: -.02em;
            line-height: 1.1;
            margin: 0 0 10px;
        }

        .dealflow-pipeline__intro {
            color: var(--text-secondary);
            font-size: 15px;
            line-height: 1.65;
            margin: 0;
            max-width: 680px;
        }

        .dealflow-pipeline__filter {
            display: flex;
            flex-direction: column;
            gap: 14px;
        }

        .dealflow-pipeline__search .input-group {
            width: 100%;
        }

        .dealflow-pipeline__search .form-control {
            background: var(--field-01);
            border-color: var(--border-subtle-02);
            color: var(--text-primary);
            height: 42px;
        }

        .dealflow-pipeline__search .btn {
            min-width: 88px;
        }

        .dealflow-pipeline__search-hint {
            color: var(--text-secondary);
            font-size: 12px;
            margin: 0;
        }

        .dealflow-pipeline__search-meta {
            align-items: center;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            justify-content: space-between;
        }

        .dealflow-pipeline__search-chip {
            background: var(--layer-accent-01);
            border: 1px solid var(--border-subtle-01);
            border-radius: 999px;
            color: var(--text-primary);
            display: inline-flex;
            font-size: 12px;
            font-weight: 600;
            padding: 6px 10px;
        }

        .dealflow-pipeline__clear {
            color: var(--link-primary);
            font-size: 12px;
            font-weight: 600;
        }

        .dealflow-pipeline__stats {
            display: grid;
            gap: 12px;
            grid-template-columns: repeat(3, minmax(0, 1fr));
            margin-top: 22px;
        }

        .dealflow-pipeline__stat {
            background: var(--background);
            border: 1px solid var(--border-subtle-01);
            border-radius: 14px;
            min-height: 92px;
            padding: 16px 18px;
        }

        .dealflow-pipeline__stat-label {
            color: var(--text-secondary);
            display: block;
            font-size: 12px;
            font-weight: 600;
            margin-bottom: 10px;
            text-transform: uppercase;
        }

        .dealflow-pipeline__stat-value {
            color: var(--text-primary);
            font-size: 22px;
            font-weight: 700;
            letter-spacing: -.02em;
            line-height: 1.15;
        }

        .dealflow-pipeline__board-shell {
            background: var(--layer-02);
            border: 1px solid var(--border-subtle-01);
            border-radius: var(--border-radius-lg);
            overflow: hidden;
            padding: 22px;
        }

        .dealflow-pipeline__board-header {
            align-items: center;
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            justify-content: space-between;
            margin-bottom: 18px;
        }

        .dealflow-pipeline__board-title {
            color: var(--text-primary);
            font-size: 18px;
            font-weight: 700;
            margin: 0;
        }

        .dealflow-pipeline__board-note {
            color: var(--text-secondary);
            font-size: 13px;
            margin: 0;
        }

        .dealflow-pipeline__board {
            display: flex;
            gap: 18px;
            overflow-x: auto;
            padding-bottom: 6px;
        }

        .dealflow-pipeline__board::-webkit-scrollbar {
            height: 10px;
        }

        .dealflow-pipeline__board::-webkit-scrollbar-thumb {
            background: var(--border-subtle-02);
            border-radius: 999px;
        }

        .dealflow-pipeline-stage {
            background: var(--layer-01);
            border: 1px solid var(--border-subtle-01);
            border-radius: var(--border-radius-md);
            display: flex;
            flex: 0 0 320px;
            flex-direction: column;
            min-height: 520px;
            overflow: hidden;
        }

        .dealflow-pipeline-stage--won {
            background: linear-gradient(180deg, var(--label-background-green) 0%, var(--layer-01) 26%);
        }

        .dealflow-pipeline-stage--lost {
            background: linear-gradient(180deg, var(--label-background-red) 0%, var(--layer-01) 26%);
        }

        .dealflow-pipeline-stage__header {
            align-items: flex-start;
            border-bottom: 1px solid var(--border-subtle-01);
            display: flex;
            gap: 14px;
            justify-content: space-between;
            padding: 18px 18px 14px;
        }

        .dealflow-pipeline-stage__eyebrow {
            color: var(--text-secondary);
            font-size: 11px;
            font-weight: 700;
            letter-spacing: .08em;
            margin-bottom: 6px;
            text-transform: uppercase;
        }

        .dealflow-pipeline-stage__title {
            color: var(--text-primary);
            font-size: 17px;
            font-weight: 700;
            line-height: 1.2;
            margin: 0;
        }

        .dealflow-pipeline-stage__count {
            align-items: center;
            background: var(--layer-accent-01);
            border: 1px solid var(--border-subtle-01);
            border-radius: 999px;
            color: var(--text-primary);
            display: inline-flex;
            font-size: 12px;
            font-weight: 700;
            justify-content: center;
            min-width: 36px;
            padding: 6px 10px;
        }

        .dealflow-pipeline-stage__summary {
            align-items: center;
            color: var(--text-secondary);
            display: flex;
            flex-wrap: wrap;
            font-size: 12px;
            gap: 10px;
            justify-content: space-between;
            padding: 12px 18px 0;
        }

        .dealflow-pipeline-stage__body {
            display: flex;
            flex: 1 1 auto;
            flex-direction: column;
            gap: 14px;
            min-height: 220px;
            padding: 18px;
            transition: background-color .16s ease, border-color .16s ease;
        }

        .dealflow-pipeline-stage__body.is-drop-target {
            background: var(--layer-accent-01);
        }

        .dealflow-pipeline-stage__empty {
            align-items: center;
            border: 1px dashed var(--border-subtle-02);
            border-radius: 14px;
            color: var(--text-secondary);
            display: flex;
            flex: 1 1 auto;
            font-size: 13px;
            justify-content: center;
            line-height: 1.6;
            min-height: 180px;
            padding: 24px 18px;
            text-align: center;
        }

        .dealflow-pipeline-card {
            background: var(--background);
            border: 1px solid var(--border-subtle-01);
            border-radius: var(--border-radius-md);
            box-shadow: 0 10px 30px -24px rgba(0, 0, 0, .55);
            cursor: grab;
            display: flex;
            flex-direction: column;
            gap: 14px;
            padding: 16px;
            transition: border-color .16s ease, box-shadow .16s ease, transform .16s ease, opacity .16s ease;
        }

        .dealflow-pipeline-card:hover {
            border-color: var(--border-interactive);
            box-shadow: 0 18px 34px -26px rgba(0, 0, 0, .6);
            transform: translateY(-1px);
        }

        .dealflow-pipeline-card:focus-visible {
            border-color: var(--border-interactive);
            box-shadow: 0 0 0 2px var(--layer-01), 0 0 0 4px var(--border-interactive);
            outline: 0;
        }

        .dealflow-pipeline-card.is-dragging-source {
            opacity: .14;
        }

        .dealflow-pipeline-card.is-submitting {
            border-color: var(--border-interactive);
            opacity: .7;
            pointer-events: none;
        }

        .dealflow-pipeline-card--preview {
            box-shadow: 0 26px 54px -28px rgba(0, 0, 0, .75);
            cursor: grabbing;
            margin: 0;
            pointer-events: none;
            transform: rotate(1.5deg) scale(1.02);
            z-index: 50;
        }

        .dealflow-pipeline-card__placeholder {
            background: var(--layer-accent-01);
            border: 1px dashed var(--border-interactive);
            border-radius: var(--border-radius-md);
        }

        .dealflow-pipeline-stage__empty.is-hidden-during-drag {
            display: none;
        }

        .dealflow-pipeline-card__header {
            align-items: flex-start;
            display: flex;
            gap: 14px;
            justify-content: space-between;
        }

        .dealflow-pipeline-card__heading {
            flex: 1 1 auto;
            min-width: 0;
        }

        .dealflow-pipeline-card__top {
            align-items: center;
            display: flex;
            gap: 10px;
            justify-content: space-between;
        }

        .dealflow-pipeline-card__status {
            border: 1px solid var(--border-subtle-02);
            border-radius: 999px;
            color: var(--text-primary);
            display: inline-flex;
            font-size: 11px;
            font-weight: 700;
            letter-spacing: .06em;
            padding: 6px 10px;
            text-transform: uppercase;
        }

        .dealflow-pipeline-card__health {
            border-radius: 50%;
            display: inline-block;
            flex-shrink: 0;
            height: 10px;
            width: 10px;
        }

        .dealflow-pipeline-card__health--green {
            background: var(--label-color-green, #24805c);
        }

        .dealflow-pipeline-card__health--yellow {
            background: #d4a017;
        }

        .dealflow-pipeline-card__health--red {
            background: var(--label-color-red, #bc4f4f);
        }

        .dealflow-pipeline-card__status--open {
            background: var(--label-background-blue);
            border-color: var(--label-border-blue);
            color: var(--label-color-blue);
        }

        .dealflow-pipeline-card__status--won {
            background: var(--label-background-green);
            border-color: var(--label-border-green);
            color: var(--label-color-green);
        }

        .dealflow-pipeline-card__status--lost {
            background: var(--label-background-red);
            border-color: var(--label-border-red);
            color: var(--label-color-red);
        }

        .dealflow-pipeline-card__date {
            color: var(--text-secondary);
            font-size: 12px;
            font-weight: 600;
        }

        .dealflow-pipeline-card__title {
            color: var(--text-primary);
            display: inline-block;
            font-size: 18px;
            font-weight: 700;
            letter-spacing: -.02em;
            line-height: 1.25;
            text-decoration: none;
        }

        .dealflow-pipeline-card__title:hover,
        .dealflow-pipeline-card__title:focus {
            color: var(--link-primary);
            text-decoration: none;
        }

        .dealflow-pipeline-card__title-row {
            margin-top: -2px;
        }

        .dealflow-pipeline-card__company {
            color: var(--text-secondary);
            font-size: 13px;
            line-height: 1.5;
            margin-top: 8px;
        }

        .dealflow-pipeline-card__amount {
            color: var(--text-primary);
            flex: 0 0 auto;
            font-size: 24px;
            font-weight: 700;
            letter-spacing: -.03em;
            line-height: 1.05;
            padding-left: 12px;
            text-align: right;
        }

        .dealflow-pipeline-card__details {
            color: var(--text-secondary);
            display: flex;
            font-size: 13px;
            gap: 6px;
            margin-top: 4px;
        }

        @media (max-width: 991px) {
            .dealflow-pipeline__hero-grid {
                grid-template-columns: 1fr;
            }

            .dealflow-pipeline__stats {
                grid-template-columns: 1fr;
            }

            .dealflow-pipeline__board-shell {
                padding: 18px;
            }

            .dealflow-pipeline-stage {
                flex-basis: min(320px, calc(100vw - 72px));
            }
        }

        @media (max-width: 767px) {
            .dealflow-pipeline__hero,
            .dealflow-pipeline__board-shell {
                padding: 18px;
            }

            .dealflow-pipeline__title {
                font-size: 28px;
            }

            .dealflow-pipeline-stage {
                flex-basis: calc(100vw - 52px);
            }
        }
    </style>

    <div class="dealflow-pipeline">
        <section class="dealflow-pipeline__hero">
            <div class="dealflow-pipeline__hero-grid">
                <div>
                    <div class="dealflow-pipeline__eyebrow">Pipeline</div>
                    <h2 class="dealflow-pipeline__title">{{ selectedPipeline.getName() }}</h2>
                    <p class="dealflow-pipeline__intro">{{ selectedPipeline.getName() }} pipeline</p>
                </div>

                <div class="dealflow-pipeline__filter">
                    <form class="dealflow-pipeline__search" method="get" action="{{ path('mautic_dealflow_pipeline') }}" data-dealflow-live-search>
                        <div class="input-group">
                            <input
                                class="form-control"
                                type="search"
                                name="search"
                                value="{{ searchValue }}"
                                placeholder="Search deals, companies, owners, or sources"
                                autocomplete="off"
                                data-dealflow-live-search-input
                            >
                        </div>
                    </form>
                    <div class="dealflow-pipeline__search-meta">
                        <div>
                            {% if searchValue %}
                                <span class="dealflow-pipeline__search-chip">Filtered by "{{ searchValue }}"</span>
                                <a class="dealflow-pipeline__clear" href="{{ path('mautic_dealflow_pipeline') }}" data-toggle="ajax">Clear</a>
                            {% else %}
                                <span class="dealflow-pipeline__search-chip">Showing all active deals</span>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>

            <div class="dealflow-pipeline__stats" style="grid-template-columns: repeat(4, minmax(0, 1fr));">
                <div class="dealflow-pipeline__stat">
                    <span class="dealflow-pipeline__stat-label">Total Deals</span>
                    <div class="dealflow-pipeline__stat-value">{{ totalDeals }}</div>
                </div>
                <div class="dealflow-pipeline__stat">
                    <span class="dealflow-pipeline__stat-label">Total Pipeline Value</span>
                    <div class="dealflow-pipeline__stat-value">{{ include('@DealFlow/Deal/_amount.html.twig', {amount: totalPipelineValue|default(0), currency: 'USD', compact: true}, false) }}</div>
                </div>
                <div class="dealflow-pipeline__stat">
                    <span class="dealflow-pipeline__stat-label">Stages With Deals</span>
                    <div class="dealflow-pipeline__stat-value">{{ populatedStages }}</div>
                </div>
                <div class="dealflow-pipeline__stat">
                    <span class="dealflow-pipeline__stat-label">Open Stages</span>
                    <div class="dealflow-pipeline__stat-value">{{ openStages }}</div>
                </div>
            </div>
        </section>

        <section class="dealflow-pipeline__board-shell">
            <div class="dealflow-pipeline__board-header">
                <div>
                    <h3 class="dealflow-pipeline__board-title">Pipeline Board</h3>
                </div>
            </div>

            <div class="dealflow-pipeline__board" data-dealflow-board>
                {% for column in columns %}
                    <section class="dealflow-pipeline-stage dealflow-pipeline-stage--{{ column.stage.getStageType() }}" data-stage-id="{{ column.stage.getId() }}">
                        <div class="dealflow-pipeline-stage__header">
                            <div>
                                <div class="dealflow-pipeline-stage__eyebrow">{{ column.stage.getStageType()|upper }}</div>
                                <h4 class="dealflow-pipeline-stage__title">{{ column.stage.getName() }}</h4>
                            </div>
                            <span class="dealflow-pipeline-stage__count" data-stage-count>{{ column.deals|length }}</span>
                        </div>

                        <div class="dealflow-pipeline-stage__summary">
                            <span data-stage-summary-count>{{ column.deals|length }} deal{{ column.deals|length == 1 ? '' : 's' }}</span>
                            <span>{{ column.stage.getStageType()|title }} stage</span>
                        </div>

                        <div class="dealflow-pipeline-stage__body" data-stage-dropzone="{{ column.stage.getId() }}">
                            {% if column.deals is empty %}
                                <div class="dealflow-pipeline-stage__empty">No deals</div>
                            {% else %}
                                {% for deal in column.deals %}
                                    {% set context = dealContexts[deal.getId()] ?? {'companyName': null, 'ownerName': null, 'contacts': []} %}
                                    {% set canEditDeal = editableDealIds[deal.getId()] ?? false %}
                                    {% set shortAmount = include('@DealFlow/Deal/_amount.html.twig', {amount: deal.getAmount(), currency: deal.getCurrency(), compact: true}, false)|trim %}
                                    <article
                                        class="dealflow-pipeline-card"
                                        draggable="{{ canEditDeal ? 'true' : 'false' }}"
                                        data-deal-card
                                        data-deal-id="{{ deal.getId() }}"
                                        data-current-stage-id="{{ deal.getStage() ? deal.getStage().getId() : '' }}"
                                        data-view-url="{{ path('mautic_dealflow_view', {'objectId': deal.getId()}) }}"
                                        tabindex="0"
                                        role="link"
                                        aria-label="Open {{ deal.getTitle() }}"
                                    >
                                        <div class="dealflow-pipeline-card__header">
                                            <div class="dealflow-pipeline-card__heading">
                                                <div class="dealflow-pipeline-card__top">
                                                    <span class="dealflow-pipeline-card__status dealflow-pipeline-card__status--{{ deal.getStatus() }}">{{ deal.getStatus()|title }}</span>
                                                    {% set healthColor = dealHealthIndicators[deal.getId()] ?? 'green' %}
                                                    <span class="dealflow-pipeline-card__health dealflow-pipeline-card__health--{{ healthColor }}" title="{{ healthColor|title }} health"></span>
                                                </div>
                                            </div>

                                            <div class="dealflow-pipeline-card__amount">
                                                {{ shortAmount }}
                                            </div>
                                        </div>

                                        <div class="dealflow-pipeline-card__title-row">
                                            <a class="dealflow-pipeline-card__title" href="{{ path('mautic_dealflow_view', {'objectId': deal.getId()}) }}" data-toggle="ajax" draggable="false">{{ deal.getTitle() }}</a>
                                            <div class="dealflow-pipeline-card__company">{{ context.companyName ?: 'No company linked' }}</div>
                                            <div class="dealflow-pipeline-card__details">
                                                <span>{{ context.ownerName ?: 'Unassigned' }}</span>
                                                {% if deal.getConfidence() is not null %}
                                                    <span>&middot; {{ deal.getConfidence() }}%</span>
                                                {% endif %}
                                            </div>
                                        </div>

                                        {% if canEditDeal %}
                                            <form class="dealflow-pipeline-card__move" method="post" action="{{ path('mautic_dealflow_move_stage', {'objectId': deal.getId()}) }}" data-stage-form hidden>
                                                <input type="hidden" name="_token" value="{{ csrf_token('dealflow_move_stage_' ~ deal.getId()) }}">
                                                <input type="hidden" name="return_url" value="{{ searchValue ? path('mautic_dealflow_pipeline', {'search': searchValue}) : path('mautic_dealflow_pipeline') }}">
                                                <div class="input-group input-group-sm">
                                                    <select name="stage_id" class="form-control" data-stage-select>
                                                        {% for stage in stages %}
                                                            <option value="{{ stage.getId() }}" {{ deal.getStage() and stage.getId() == deal.getStage().getId() ? 'selected' : '' }}>
                                                                {{ stage.getName() }}
                                                            </option>
                                                        {% endfor %}
                                                    </select>
                                                    <span class="input-group-btn">
                                                        <button class="btn btn-default" type="submit">Move</button>
                                                    </span>
                                                </div>
                                            </form>
                                        {% endif %}
                                    </article>
                                {% endfor %}
                            {% endif %}
                        </div>
                    </section>
                {% endfor %}
            </div>
        </section>
    </div>

    {{ include('@DealFlow/_scripts.html.twig') }}

    <script>
        (function () {
            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, 250);
                });

                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();
                });
            }

            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('.dealflow-pipeline-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('.dealflow-pipeline-stage__empty');
                if (emptyState) {
                    dropzone.insertBefore(dragPlaceholder, emptyState);
                } else if (dragPlaceholder.parentNode !== dropzone) {
                    dropzone.appendChild(dragPlaceholder);
                }
            };

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

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

                if (!countElement || !summaryElement) {
                    return;
                }

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

            board.querySelectorAll('[data-deal-card]').forEach(function (card) {
                var openCard = function () {
                    var titleLink = card.querySelector('.dealflow-pipeline-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 = 'dealflow-pipeline-card__placeholder';
                    dragPlaceholder.style.height = card.offsetHeight + 'px';
                    card.parentNode.insertBefore(dragPlaceholder, card.nextSibling);

                    dragPreview = card.cloneNode(true);
                    dragPreview.classList.add('dealflow-pipeline-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('.dealflow-pipeline-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;
                    }

                    // Extract form data BEFORE any DOM manipulation — moving the card
                    // can detach the form element, causing querySelector to fail.
                    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 — form not found. Try refreshing.');
                        clearDropTargets();
                        removeDragArtifacts();
                        return;
                    }

                    // Capture the form action URL and build form data before DOM changes
                    var formAction = form.getAttribute('action');
                    select.value = targetStageId;
                    var formData = new FormData(form);
                    var boardScrollLeft = board.scrollLeft;

                    var sourceStage = draggedCard.closest('.dealflow-pipeline-stage');
                    var targetStage = dropzone.closest('.dealflow-pipeline-stage');
                    var targetEmptyState = dropzone.querySelector('.dealflow-pipeline-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'});

                    updateStageCounts(sourceStage, -1);
                    updateStageCounts(targetStage, 1);
                    draggedCard.setAttribute('data-current-stage-id', targetStageId);
                    clearDropTargets();
                    removeDragArtifacts();

                    // AJAX submit with pre-captured form data
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', formAction);
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

                    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) {
                                    ok = false;
                                    rollbackDragDrop(movedCard, sourceStage, targetStage, currentStageId);
                                    showToast('Failed: ' + (resp.error || 'Unknown error'));
                                    return;
                                }
                            } catch (e) { /* non-JSON response, treat as success if 2xx */ }
                            movedCard.setAttribute('data-current-stage-id', targetStageId);
                            board.scrollLeft = boardScrollLeft;
                        } 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);
                });
            });
        })();
    </script>
{% endblock %}
