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

{% block headerTitle selectedPipeline.getName() %}

{% block actions %}
    <div style="display:flex;align-items:center;gap:10px;">
        <form class="dfp-search" method="get" action="{{ path('mautic_dealflow_pipeline') }}" data-dealflow-live-search>
            <svg class="dfp-search__icon" width="14" height="14" viewBox="0 0 16 16" fill="none"><circle cx="7" cy="7" r="5.5" stroke="currentColor" stroke-width="1.4"/><path d="M11 11l3.5 3.5" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"/></svg>
            <input
                class="dfp-search__input"
                type="search"
                name="search"
                value="{{ searchValue }}"
                placeholder="Search deals..."
                autocomplete="off"
                data-dealflow-live-search-input
            >
        </form>
        {% 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 %}
    </div>
{% endblock %}

{% block content %}
    {{ include('@DealFlow/_styles.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 %}

    {# ── Compute pipeline summary stats ── #}
    {% set openDealCount = 0 %}
    {% set openDealValue = 0 %}
    {% set wonDealValue = 0 %}
    {% for column in columns %}
        {% for deal in column.deals %}
            {% if column.stage.getStageType() == 'open' %}
                {% set openDealCount = openDealCount + 1 %}
                {% set openDealValue = openDealValue + (deal.getAmount() ?? 0) %}
            {% elseif column.stage.getStageType() == 'won' %}
                {% set wonDealValue = wonDealValue + (deal.getAmount() ?? 0) %}
            {% endif %}
        {% endfor %}
    {% endfor %}
    {% set avgDealValue = openDealCount > 0 ? openDealValue / openDealCount : 0 %}

    <style>
        /* ── V3 Pipeline Kanban — Clean rewrite ── */

        /* Search in actions bar */
        .dfp-search {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 6px 12px;
            background: var(--layer-02, #f4f5f7);
            border: 1px solid var(--border-subtle-01, #e1e3e8);
            border-radius: 6px;
            transition: border-color 0.15s;
        }
        .dfp-search:focus-within {
            border-color: var(--button-primary);
        }
        .dfp-search__icon {
            color: var(--text-secondary, #5e6278);
            flex-shrink: 0;
        }
        .dfp-search__input {
            border: none;
            background: transparent;
            font-size: 13px;
            color: var(--text-primary, #1a1a2e);
            outline: none;
            width: 160px;
            font-family: inherit;
        }
        .dfp-search__input::placeholder {
            color: var(--text-secondary, #5e6278);
        }

        /* Pipeline wrapper */
        .dfp {
            color: var(--text-primary, #1a1a2e);
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
        }

        /* ── Summary bar ── */
        .dfp-summary {
            display: flex;
            align-items: center;
            gap: 20px;
            padding: 10px 0;
            margin: 0;
            border-top: 1px solid var(--border-subtle-01, #e1e3e8);
            border-bottom: 1px solid var(--border-subtle-01, #e1e3e8);
        }
        .dfp-summary__stat {
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .dfp-summary__label {
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.08em;
            color: var(--text-secondary, #5e6278);
            white-space: nowrap;
        }
        .dfp-summary__value {
            font-size: 14px;
            font-weight: 700;
            color: var(--text-primary, #1a1a2e);
            white-space: nowrap;
        }
        .dfp-summary__value--green { color: var(--label-color-green, #137333); }
        .dfp-summary__divider {
            width: 1px;
            height: 16px;
            background: var(--border-subtle-02, #d0d3da);
            flex-shrink: 0;
        }

        /* ── Velocity bar ── */
        .dfp-velocity {
            display: flex;
            align-items: center;
            gap: 16px;
            padding: 10px 0;
            margin-bottom: 12px;
            border-bottom: 1px solid var(--border-subtle-01, #e1e3e8);
        }
        .dfp-velocity__label {
            font-size: 11px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: var(--text-secondary, #5e6278);
            white-space: nowrap;
        }
        .dfp-velocity__pills {
            display: flex;
            gap: 6px;
        }
        .dfp-velocity__pill {
            padding: 3px 10px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 600;
            border: 1px solid var(--border-subtle-01, #e1e3e8);
            background: var(--background, #ffffff);
            color: var(--text-secondary, #5e6278);
            cursor: pointer;
            transition: all 0.15s;
        }
        .dfp-velocity__pill.is-active {
            background: var(--label-background-blue, #e8f0fe);
            color: var(--label-color-blue, #1a56db);
            border-color: var(--label-color-blue, #1a56db);
        }
        .dfp-velocity__pill:hover {
            border-color: var(--button-primary);
        }
        .dfp-velocity__track {
            flex: 1;
            display: flex;
            align-items: center;
            gap: 4px;
            height: 22px;
            background: var(--layer-02, #f4f5f7);
            border-radius: 11px;
            padding: 0 4px;
            overflow: hidden;
        }
        .dfp-velocity__seg {
            height: 14px;
            border-radius: 7px;
            transition: width 0.3s ease;
        }
        .dfp-velocity__seg--fwd { background: var(--button-primary); opacity: 0.8; }
        .dfp-velocity__seg--won { background: var(--label-color-green, #137333); opacity: 0.8; }
        .dfp-velocity__seg--lost { background: var(--label-color-red, #c5221f); opacity: 0.6; }
        .dfp-velocity__metrics {
            display: flex;
            align-items: center;
            gap: 14px;
            flex-shrink: 0;
        }
        .dfp-velocity__metric {
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 12px;
            font-weight: 600;
            color: var(--text-secondary, #5e6278);
        }
        .dfp-velocity__metric-dot {
            width: 7px;
            height: 7px;
            border-radius: 50%;
        }
        .dfp-velocity__metric-val {
            font-size: 13px;
            font-weight: 700;
            color: var(--text-primary, #1a1a2e);
        }

        /* ── Filter chip ── */
        .dfp-filter {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 8px 0;
        }
        .dfp-filter__chip {
            background: var(--layer-accent-01, #f4f5f7);
            border: 1px solid var(--border-subtle-01, #e1e3e8);
            border-radius: 999px;
            color: var(--text-primary, #1a1a2e);
            font-size: 12px;
            font-weight: 600;
            padding: 4px 10px;
        }
        .dfp-filter__clear {
            color: var(--link-primary);
            font-size: 12px;
            font-weight: 600;
        }

        /* ── Board ── */
        .dfp-board {
            display: flex;
            gap: 0;
            overflow-x: auto;
            background: var(--background, #ffffff);
            padding-bottom: 6px;
        }
        .dfp-board::-webkit-scrollbar { height: 8px; }
        .dfp-board::-webkit-scrollbar-thumb { background: var(--border-subtle-02, #d0d3da); border-radius: 4px; }

        /* ── Stage column ── */
        .dfp-stage {
            flex: 0 0 220px;
            min-width: 220px;
            display: flex;
            flex-direction: column;
            background: transparent;
            border-right: 1px solid var(--border-subtle-01, #e1e3e8);
            min-height: 400px;
        }
        .dfp-stage:last-child { border-right: none; }
        .dfp-stage--won { background: rgba(230, 244, 234, 0.4); }
        .dfp-stage--lost { background: rgba(252, 232, 230, 0.4); }

        /* Stage header */
        .dfp-stage__hdr {
            padding: 14px 14px 10px;
            border-bottom: 1px solid var(--border-subtle-01, #e1e3e8);
        }
        .dfp-stage__hdr-top {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 4px;
        }
        .dfp-stage__name {
            font-size: 12px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: var(--text-secondary, #5e6278);
            margin: 0;
        }
        .dfp-stage--won .dfp-stage__name { color: var(--label-color-green, #137333); }
        .dfp-stage--lost .dfp-stage__name { color: var(--label-color-red, #c5221f); }
        .dfp-stage__count {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            min-width: 22px;
            height: 22px;
            border-radius: 6px;
            font-size: 11px;
            font-weight: 700;
            background: var(--background, #ffffff);
            color: var(--text-secondary, #5e6278);
            border: 1px solid var(--border-subtle-01, #e1e3e8);
            padding: 0 6px;
        }
        .dfp-stage--won .dfp-stage__count {
            background: var(--label-background-green, #e6f4ea);
            color: var(--label-color-green, #137333);
        }
        .dfp-stage--lost .dfp-stage__count {
            background: var(--label-background-red, #fce8e6);
            color: var(--label-color-red, #c5221f);
        }
        .dfp-stage__total {
            font-size: 16px;
            font-weight: 700;
            letter-spacing: -0.02em;
            color: var(--text-primary, #1a1a2e);
        }
        .dfp-stage--won .dfp-stage__total { color: var(--label-color-green, #137333); }
        .dfp-stage--lost .dfp-stage__total { color: var(--label-color-red, #c5221f); }

        /* Stage body (dropzone) */
        .dfp-stage__body {
            display: flex;
            flex: 1 1 auto;
            flex-direction: column;
            gap: 10px;
            padding: 12px;
            min-height: 180px;
            transition: background-color .16s ease;
        }
        .dfp-stage__body.is-drop-target {
            background: var(--layer-accent-01, rgba(78,110,242,0.06));
        }
        .dfp-stage__empty {
            display: flex;
            align-items: center;
            justify-content: center;
            flex: 1 1 auto;
            min-height: 120px;
            border: 1px dashed var(--border-subtle-02, #d0d3da);
            border-radius: 8px;
            color: var(--text-secondary, #5e6278);
            font-size: 13px;
        }
        .dfp-stage__empty.is-hidden-during-drag { display: none; }

        /* ── Deal card ── */
        .dfp-card {
            background: var(--background, #ffffff);
            border: 1px solid var(--border-subtle-01, #e1e3e8);
            border-radius: 8px;
            padding: 12px;
            cursor: grab;
            transition: border-color .15s, box-shadow .15s, transform .15s, opacity .15s;
        }
        .dfp-card:hover {
            border-color: var(--border-interactive);
            box-shadow: 0 2px 8px rgba(0,0,0,0.06);
            transform: translateY(-1px);
        }
        .dfp-card:focus-visible {
            border-color: var(--border-interactive);
            box-shadow: 0 0 0 2px var(--background, #ffffff), 0 0 0 4px var(--border-interactive);
            outline: 0;
        }
        .dfp-card.is-dragging-source { opacity: .14; }
        .dfp-card.is-submitting { border-color: var(--border-interactive); opacity: .7; pointer-events: none; }
        .dfp-card--preview {
            box-shadow: 0 26px 54px -28px rgba(0,0,0,.75);
            cursor: grabbing;
            pointer-events: none;
            transform: rotate(1.5deg) scale(1.02);
            z-index: 50;
        }
        .dfp-card__placeholder {
            background: var(--layer-accent-01, rgba(78,110,242,0.06));
            border: 1px dashed var(--border-interactive);
            border-radius: 8px;
        }

        /* Card: timestamp */
        .dfp-card__time {
            font-size: 11px;
            font-weight: 600;
            color: var(--text-secondary, #5e6278);
            margin-bottom: 6px;
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .dfp-card__time svg { width: 12px; height: 12px; flex-shrink: 0; }

        /* Card: title */
        .dfp-card__title {
            font-size: 14px;
            font-weight: 700;
            color: var(--text-primary, #1a1a2e);
            margin-bottom: 4px;
            line-height: 1.3;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-decoration: none;
        }
        .dfp-card__title:hover,
        .dfp-card__title:focus {
            color: var(--link-primary);
            text-decoration: none;
        }

        /* Card: company */
        .dfp-card__company {
            font-size: 12px;
            color: var(--text-secondary, #5e6278);
            margin-bottom: 6px;
        }

        /* Card: meta row */
        .dfp-card__meta {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 8px;
        }
        .dfp-card__amount {
            font-size: 14px;
            font-weight: 700;
            letter-spacing: -0.02em;
            color: var(--text-primary, #1a1a2e);
        }
        .dfp-card__health-wrap {
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .dfp-card__health {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            display: inline-block;
        }
        .dfp-card__health--green { background: var(--label-color-green, #137333); }
        .dfp-card__health--yellow { background: #e8a317; }
        .dfp-card__health--red { background: var(--label-color-red, #c5221f); }

        /* Card: won/lost pill */
        .dfp-card__status {
            display: inline-flex;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 11px;
            font-weight: 600;
        }
        .dfp-card__status--won { background: var(--label-background-green, #e6f4ea); color: var(--label-color-green, #137333); }
        .dfp-card__status--lost { background: var(--label-background-red, #fce8e6); color: var(--label-color-red, #c5221f); }

        /* Card: days in stage */
        .dfp-card__days {
            font-size: 11px;
            font-weight: 500;
            color: var(--text-secondary, #5e6278);
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px solid var(--border-subtle-01, #e1e3e8);
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .dfp-card__days svg { width: 12px; height: 12px; flex-shrink: 0; }

        /* ── Responsive ── */
        @media (max-width: 767px) {
            .dfp-stage { min-width: calc(100vw - 52px); max-width: calc(100vw - 52px); }
            .dfp-summary { flex-wrap: wrap; gap: 10px; }
            .dfp-velocity { flex-wrap: wrap; }
        }
    </style>

    <div class="dfp">
        {# ── Summary bar ── #}
        <div class="dfp-summary">
            <div class="dfp-summary__stat">
                <span class="dfp-summary__label">Open Deals</span>
                <span class="dfp-summary__value">{{ openDealCount }}</span>
            </div>
            <span class="dfp-summary__divider"></span>
            <div class="dfp-summary__stat">
                <span class="dfp-summary__label">Open Value</span>
                <span class="dfp-summary__value">{{ include('@DealFlow/Deal/_amount.html.twig', {amount: openDealValue, currency: 'USD', compact: true}, false) }}</span>
            </div>
            <span class="dfp-summary__divider"></span>
            <div class="dfp-summary__stat">
                <span class="dfp-summary__label">Avg Deal</span>
                <span class="dfp-summary__value">{{ include('@DealFlow/Deal/_amount.html.twig', {amount: avgDealValue, currency: 'USD', compact: true}, false) }}</span>
            </div>
            <span class="dfp-summary__divider"></span>
            <div class="dfp-summary__stat">
                <span class="dfp-summary__label">Won</span>
                <span class="dfp-summary__value dfp-summary__value--green">{{ include('@DealFlow/Deal/_amount.html.twig', {amount: wonDealValue, currency: 'USD', compact: true}, false) }}</span>
            </div>
        </div>

        {# ── Velocity bar ── #}
        {% set v14 = pipelineVelocity[14]|default({fwd: 0, won: 0, lost: 0, fwdPct: '0%', wonPct: '0%', lostPct: '0%'}) %}
        <div class="dfp-velocity">
            <span class="dfp-velocity__label">Pipeline Velocity</span>
            <div class="dfp-velocity__pills">
                <span class="dfp-velocity__pill" data-velocity-period="7">7d</span>
                <span class="dfp-velocity__pill is-active" data-velocity-period="14">14d</span>
                <span class="dfp-velocity__pill" data-velocity-period="30">30d</span>
            </div>
            <div class="dfp-velocity__track">
                <div class="dfp-velocity__seg dfp-velocity__seg--fwd" style="width:{{ v14.fwdPct }}" data-velocity-seg="fwd"></div>
                <div class="dfp-velocity__seg dfp-velocity__seg--won" style="width:{{ v14.wonPct }}" data-velocity-seg="won"></div>
                <div class="dfp-velocity__seg dfp-velocity__seg--lost" style="width:{{ v14.lostPct }}" data-velocity-seg="lost"></div>
            </div>
            <div class="dfp-velocity__metrics">
                <div class="dfp-velocity__metric">
                    <span class="dfp-velocity__metric-dot" style="background:var(--button-primary);"></span>
                    <span class="dfp-velocity__metric-val" data-velocity-val="fwd">{{ v14.fwd }}</span>
                    <span>moved</span>
                </div>
                <div class="dfp-velocity__metric">
                    <span class="dfp-velocity__metric-dot" style="background:var(--label-color-green,#137333);"></span>
                    <span class="dfp-velocity__metric-val" data-velocity-val="won">{{ v14.won }}</span>
                    <span>won</span>
                </div>
                <div class="dfp-velocity__metric">
                    <span class="dfp-velocity__metric-dot" style="background:var(--label-color-red,#c5221f);"></span>
                    <span class="dfp-velocity__metric-val" data-velocity-val="lost">{{ v14.lost }}</span>
                    <span>lost</span>
                </div>
            </div>
        </div>

        {# ── Filter chip ── #}
        {% if searchValue %}
            <div class="dfp-filter">
                <span class="dfp-filter__chip">Filtered by "{{ searchValue }}"</span>
                <a class="dfp-filter__clear" href="{{ path('mautic_dealflow_pipeline') }}" data-toggle="ajax">Clear</a>
            </div>
        {% endif %}

        {# ── Board ── #}
        <div class="dfp-board" data-dealflow-board>
            {% for column in columns %}
                {% set stageTotal = 0 %}
                {% for deal in column.deals %}
                    {% set stageTotal = stageTotal + (deal.getAmount() ?? 0) %}
                {% endfor %}

                <section class="dfp-stage dfp-stage--{{ column.stage.getStageType() }}" data-stage-id="{{ column.stage.getId() }}">
                    <div class="dfp-stage__hdr">
                        <div class="dfp-stage__hdr-top">
                            <h4 class="dfp-stage__name">{{ column.stage.getName() }}</h4>
                            <span class="dfp-stage__count" data-stage-count>{{ column.deals|length }}</span>
                        </div>
                        <div class="dfp-stage__total" data-stage-total="{{ stageTotal }}">{{ include('@DealFlow/Deal/_amount.html.twig', {amount: stageTotal, currency: 'USD', compact: true}, false) }}</div>
                    </div>

                    <span data-stage-summary-count style="display:none;">{{ column.deals|length }} deal{{ column.deals|length == 1 ? '' : 's' }}</span>

                    <div class="dfp-stage__body" data-stage-dropzone="{{ column.stage.getId() }}">
                        {% if column.deals is empty %}
                            <div class="dfp-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 %}
                                {% set daysInStage = date().diff(deal.getDateAdded()).days %}
                                <article
                                    class="dfp-card"
                                    draggable="{{ canEditDeal ? 'true' : 'false' }}"
                                    data-deal-card
                                    data-deal-id="{{ deal.getId() }}"
                                    data-deal-amount="{{ deal.getAmount() ?? 0 }}"
                                    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="dfp-card__time">
                                        <svg viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="6.5" stroke="currentColor" stroke-width="1.2"/><path d="M8 5v3.5l2.5 1.5" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/></svg>
                                        Entered {{ deal.getDateAdded()|date('M j') }}
                                    </div>

                                    <a class="dfp-card__title" href="{{ path('mautic_dealflow_view', {'objectId': deal.getId()}) }}" data-toggle="ajax" draggable="false">{{ deal.getTitle() }}</a>

                                    <div class="dfp-card__company">{{ context.companyName ?: 'No company linked' }}</div>

                                    <div class="dfp-card__meta">
                                        <span class="dfp-card__amount">{{ shortAmount }}</span>
                                        <div class="dfp-card__health-wrap">
                                            {% set healthColor = dealHealthIndicators[deal.getId()] ?? 'green' %}
                                            <span class="dfp-card__health dfp-card__health--{{ healthColor }}" title="{{ healthColor|title }} health"></span>
                                            {% if deal.getStatus() == 'won' %}
                                                <span class="dfp-card__status dfp-card__status--won">Won</span>
                                            {% elseif deal.getStatus() == 'lost' %}
                                                <span class="dfp-card__status dfp-card__status--lost">Lost</span>
                                            {% endif %}
                                        </div>
                                    </div>

                                    <div class="dfp-card__days">
                                        <svg viewBox="0 0 16 16" fill="none"><path d="M8 3v5l3 2" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/><circle cx="8" cy="8" r="6.5" stroke="currentColor" stroke-width="1.2"/></svg>
                                        {{ daysInStage }} day{{ daysInStage == 1 ? '' : 's' }} in stage
                                    </div>

                                    {% if canEditDeal %}
                                        <form class="dfp-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>
    </div>

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

    <script>
        (function () {
            // Velocity pill switching
            var velocityData = {{ pipelineVelocity|json_encode|raw }};
            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;
                });
            });

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

            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 scaled = abs / 1000000;
                    result = prefix + (scaled === Math.floor(scaled) ? scaled.toFixed(0) : scaled.toFixed(1)) + 'mm';
                } else if (abs >= 1000) {
                    var scaled = abs / 1000;
                    result = prefix + (scaled === Math.floor(scaled) ? scaled.toFixed(0) : scaled.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 — 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;

                            // Determine which velocity bucket this move falls into
                            var targetStageType = targetStage.classList.contains('dfp-stage--won') ? 'won'
                                : targetStage.classList.contains('dfp-stage--lost') ? 'lost'
                                : 'fwd';

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

                            // Update the bar segment widths
                            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%';
                                }
                            }

                            // Update bar segments for the currently active period
                            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);
                });
            });
        })();
    </script>
{% endblock %}
