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

{% block headerTitle pageTitle %}

{% block content %}
    {% set isModal = isModal|default(false) %}
    {% set contactRows = contactRows|default([{'contact_id': null, 'contact_name': '', 'label': ''}]) %}
    {% set contactRowErrors = contactRowErrors|default([]) %}
    {% set roleSuggestions = roleSuggestions|default([]) %}

    <style>
        .dealflow-entry-shell {
            background: var(--layer-02);
            border: 1px solid var(--border-subtle-01);
            border-radius: var(--border-radius-lg);
            box-shadow: none;
            overflow: visible;
        }

        .dealflow-entry-shell--modal {
            border: 0;
            border-radius: var(--border-radius-md);
            box-shadow: none;
        }

        {% if isModal %}
        #MauticSharedModal .modal-header {
            display: none;
        }

        #MauticSharedModal .modal-body {
            padding: 0;
        }
        {% endif %}

        .dealflow-entry-header {
            align-items: flex-start;
            background: linear-gradient(135deg, var(--layer-01) 0%, var(--layer-02) 100%);
            border-bottom: 1px solid var(--border-subtle-01);
            color: var(--text-primary);
            display: flex;
            gap: 18px;
            justify-content: space-between;
            padding: 24px 28px;
        }

        .dealflow-entry-header__eyebrow {
            color: var(--text-secondary);
            display: block;
            font-size: 11px;
            font-weight: 700;
            letter-spacing: 0.12em;
            margin-bottom: 8px;
            text-transform: uppercase;
        }

        .dealflow-entry-header__title {
            color: var(--text-primary);
            font-size: 28px;
            font-weight: 700;
            letter-spacing: -0.03em;
            line-height: 1.1;
            margin: 0 0 8px;
        }

        .dealflow-entry-header__copy {
            color: var(--text-secondary);
            margin: 0;
            max-width: 560px;
        }

        .dealflow-entry-body {
            padding: 28px;
        }

        .dealflow-entry-body--modal {
            padding-top: 24px;
        }

        .dealflow-entry-stack {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .dealflow-entry-card {
            background: var(--background);
            border: 1px solid var(--border-subtle-01);
            border-radius: var(--border-radius-md);
            box-shadow: none;
            overflow: visible;
        }

        .dealflow-entry-card__header {
            align-items: center;
            background: var(--layer-01);
            border-top-left-radius: inherit;
            border-top-right-radius: inherit;
            border-bottom: 1px solid var(--border-subtle-01);
            display: flex;
            justify-content: space-between;
            padding: 18px 20px 14px;
        }

        .dealflow-entry-card__title {
            color: var(--text-primary);
            font-size: 18px;
            font-weight: 700;
            letter-spacing: -0.02em;
            margin: 0;
        }

        .dealflow-entry-card__subtitle {
            color: var(--text-secondary);
            font-size: 13px;
            margin: 4px 0 0;
        }

        .dealflow-entry-card__body {
            border-bottom-left-radius: inherit;
            border-bottom-right-radius: inherit;
            padding: 20px;
        }

        .dealflow-entry-card .help-block {
            color: var(--text-secondary);
            font-size: 12px;
        }

        .dealflow-entry-card .form-group:last-child {
            margin-bottom: 0;
        }

        .dealflow-entry-shell .chosen-container {
            width: 100% !important;
        }

        .dealflow-entry-shell .chosen-container-active {
            z-index: 40;
        }

        .dealflow-entry-shell .chosen-drop {
            z-index: 45;
        }

        .dealflow-source-new,
        .dealflow-contact-role-custom {
            margin-top: 12px;
        }

        .dealflow-source-new.is-hidden,
        .dealflow-contact-role-custom.is-hidden {
            display: none;
        }

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

        .dealflow-contact-row {
            background: var(--layer-01);
            border: 1px solid var(--border-subtle-01);
            border-radius: var(--border-radius-sm);
            display: flex;
            flex-direction: column;
            gap: 14px;
            padding: 16px;
        }

        .dealflow-contact-row__secondary {
            align-items: end;
            display: flex;
            gap: 14px;
            justify-content: space-between;
        }

        .dealflow-contact-row__role {
            flex: 1 1 auto;
            max-width: 360px;
            min-width: 0;
        }

        .dealflow-contact-picker {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .dealflow-contact-picker__selection,
        .dealflow-contact-picker__lookup.is-hidden {
            display: none;
        }

        .dealflow-contact-picker__selection.is-active {
            align-items: center;
            background: var(--background);
            border: 1px solid var(--border-subtle-01);
            border-radius: var(--border-radius-sm);
            display: flex;
            gap: 10px;
            justify-content: space-between;
            min-height: 42px;
            padding: 8px 12px;
        }

        .dealflow-contact-pill {
            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;
            gap: 8px;
            line-height: 1.2;
            max-width: 100%;
            padding: 6px 12px;
        }

        .dealflow-contact-pill__label {
            font-size: 13px;
            font-weight: 600;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .dealflow-contact-picker__actions {
            display: flex;
            gap: 8px;
        }

        .dealflow-contact-picker__actions .btn,
        .dealflow-contact-row__remove .btn {
            white-space: nowrap;
        }

        .dealflow-contact-row__remove {
            align-items: flex-end;
            display: flex;
            flex: 0 0 auto;
        }

        .dealflow-contact-picker .form-group,
        .dealflow-contact-row__role .form-group {
            margin-bottom: 0;
        }

        .dealflow-entry-actions {
            border-top: 1px solid var(--border-subtle-01);
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            padding: 20px 28px 24px;
        }

        .dealflow-entry-errors {
            margin-bottom: 18px;
        }

        .dealflow-entry-inline-note {
            background: var(--layer-accent-01);
            border: 1px solid var(--border-subtle-01);
            border-radius: var(--border-radius-sm);
            color: var(--text-secondary);
            font-size: 13px;
            line-height: 1.5;
            margin-top: 12px;
            padding: 12px 14px;
        }

        .dealflow-entry-contact-help {
            color: var(--text-secondary);
            font-size: 12px;
            margin-bottom: 14px;
        }

        @media (max-width: 991px) {
            .dealflow-entry-header {
                flex-direction: column;
            }

            .dealflow-contact-row__secondary {
                align-items: stretch;
                flex-direction: column;
            }

            .dealflow-contact-row__remove {
                justify-content: flex-start;
            }

            .dealflow-contact-row__role {
                max-width: none;
            }
        }

        @media (max-width: 767px) {
            .dealflow-contact-picker__selection.is-active {
                align-items: flex-start;
                flex-direction: column;
            }
        }
    </style>

    {{ form_start(form, {'action': formAction|default(null)}) }}
    <div class="dealflow-entry-shell{{ isModal ? ' dealflow-entry-shell--modal' : '' }}">
        {% if isModal %}
            <div style="display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid var(--border-subtle-01);">
                <h4 style="margin:0;font-size:16px;font-weight:700;color:var(--text-primary);">{{ pageTitle }}</h4>
                <button type="button" class="btn btn-default btn-sm" data-dismiss="modal" aria-label="Close">
                    <i class="ri-close-line"></i>
                </button>
            </div>
        {% endif %}
        {% if not isModal %}
            <div class="dealflow-entry-header">
                <div>
                    <span class="dealflow-entry-header__eyebrow">{{ pageTitle == 'Edit Deal' ? 'Refine the deal' : 'Capture the opportunity' }}</span>
                    <h2 class="dealflow-entry-header__title">{{ pageTitle }}</h2>
                    <p class="dealflow-entry-header__copy">
                        Capture the commercial facts first, lock in the people behind the deal, and leave secondary clean-up for after the first save.
                    </p>
                </div>
            </div>
        {% endif %}

        <div class="dealflow-entry-body{{ isModal ? ' dealflow-entry-body--modal' : '' }}">
            {% if form.vars.errors|length > 0 %}
                <div class="alert alert-danger dealflow-entry-errors">
                    {{ form_errors(form) }}
                </div>
            {% endif %}

            <div class="dealflow-entry-stack">
                <section class="dealflow-entry-card">
                    <div class="dealflow-entry-card__header">
                        <div>
                            <h3 class="dealflow-entry-card__title">Deal basics</h3>
                            <p class="dealflow-entry-card__subtitle">Qualify the opportunity first, then connect it to the right company, owner, and source.</p>
                        </div>
                    </div>
                    <div class="dealflow-entry-card__body">
                        <div class="row">
                            <div class="col-md-12">{{ form_row(form.title) }}</div>
                        </div>
                        <div class="row">
                            <div class="col-md-5">{{ form_row(form.companyId) }}</div>
                            <div class="col-md-3">
                                {{ form_row(form.ownerId) }}
                                {% if addUserUrl is defined and addUserUrl %}
                                    <p class="help-block">
                                        <a href="{{ addUserUrl }}" target="_blank" rel="noopener noreferrer">Add user</a>
                                    </p>
                                {% endif %}
                            </div>
                            <div class="col-md-4">
                                {{ form_row(form.sourceSelection) }}
                                <div class="dealflow-source-new{% if form.sourceSelection.vars.value != '__new__' %} is-hidden{% endif %}" data-dealflow-source-new>
                                    {{ form_row(form.sourceNew) }}
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-5">{{ form_row(form.amount) }}</div>
                            <div class="col-md-3">{{ form_row(form.currency) }}</div>
                            <div class="col-md-4">{{ form_row(form.confidence) }}</div>
                        </div>
                        <div class="row">
                            <div class="col-md-4">{{ form_row(form.pipeline) }}</div>
                            <div class="col-md-4">{{ form_row(form.stage) }}</div>
                            <div class="col-md-4">{{ form_row(form.expectedCloseDate) }}</div>
                        </div>
                        <div class="dealflow-entry-inline-note">
                            Use source to track where the opportunity originated. Add a new source inline when the existing list does not fit.
                        </div>
                    </div>
                </section>

                <section class="dealflow-entry-card">
                    <div class="dealflow-entry-card__header">
                        <div>
                            <h3 class="dealflow-entry-card__title">Stakeholders</h3>
                            <p class="dealflow-entry-card__subtitle">Keep each person selection explicit, visible, and easy to revise as the deal evolves.</p>
                        </div>
                        <button class="btn btn-default btn-sm" type="button" data-dealflow-add-contact>
                            Add stakeholder
                        </button>
                    </div>
                    <div class="dealflow-entry-card__body">
                        {% if contactRowErrors is not empty %}
                            <div class="alert alert-danger">
                                {% for error in contactRowErrors %}
                                    <div>{{ error }}</div>
                                {% endfor %}
                            </div>
                        {% endif %}

                        <p class="dealflow-entry-contact-help">Pick the person first, confirm the selected contact in-place, then assign how they influence the deal.</p>

                        <div class="dealflow-contact-stack" data-dealflow-contacts>
                            {% for row in contactRows %}
                                {% set isCustomRole = row.label is not empty and row.label not in roleSuggestions %}
                                <div class="dealflow-contact-row" data-dealflow-contact-row>
                                    <div class="dealflow-contact-picker">
                                        <div class="dealflow-contact-picker__selection{% if row.contact_id %} is-active{% endif %}" data-dealflow-contact-selection>
                                            <span class="dealflow-contact-pill">
                                                <i class="ri-user-3-line"></i>
                                                <span class="dealflow-contact-pill__label" data-dealflow-contact-selected-label>{{ row.contact_name ?: 'Selected contact' }}</span>
                                            </span>
                                            <div class="dealflow-contact-picker__actions">
                                                <button class="btn btn-default btn-xs" type="button" data-dealflow-change-contact>
                                                    Change
                                                </button>
                                                <button class="btn btn-link btn-xs text-danger" type="button" data-dealflow-clear-contact>
                                                    Clear
                                                </button>
                                            </div>
                                        </div>

                                        <div class="dealflow-contact-picker__lookup{% if row.contact_id %} is-hidden{% endif %}" data-dealflow-contact-lookup-wrap>
                                            <div class="form-group">
                                                <label class="control-label" for="dealflow_contact_display_{{ loop.index0 }}">Contact</label>
                                                <input
                                                    type="hidden"
                                                    name="deal_contacts[{{ loop.index0 }}][contact_name]"
                                                    value="{{ row.contact_name }}"
                                                    data-dealflow-contact-name="true"
                                                >
                                                <input
                                                    class="form-control"
                                                    id="dealflow_contact_display_{{ loop.index0 }}"
                                                    type="text"
                                                    value="{{ row.contact_name }}"
                                                    autocomplete="off"
                                                    placeholder="Start typing a contact name"
                                                    data-toggle="field-lookup"
                                                    data-callback="updateDealFlowEntryContactSelection"
                                                    data-lookup-callback="updateDealFlowEntryContactSelection"
                                                    data-chosen-lookup="lead:contactList"
                                                    data-target="undefined"
                                                    data-no-record-message="No matching contacts found"
                                                    data-dealflow-contact-lookup="true"
                                                >
                                                <input
                                                    type="hidden"
                                                    name="deal_contacts[{{ loop.index0 }}][contact_id]"
                                                    value="{{ row.contact_id ?? '' }}"
                                                    data-dealflow-contact-id="true"
                                                >
                                            </div>
                                        </div>
                                    </div>

                                    <div class="dealflow-contact-row__secondary">
                                        <div class="dealflow-contact-row__role">
                                            <div class="form-group">
                                                <label class="control-label" for="dealflow_contact_role_select_{{ loop.index0 }}">Role</label>
                                                <select
                                                    class="form-control"
                                                    id="dealflow_contact_role_select_{{ loop.index0 }}"
                                                    name="deal_contacts[{{ loop.index0 }}][label_selection]"
                                                    data-dealflow-role-select="true"
                                                >
                                                    <option value="">Select stakeholder role</option>
                                                    {% for role in roleSuggestions %}
                                                        <option value="{{ role }}"{% if row.label == role %} selected{% endif %}>{{ role }}</option>
                                                    {% endfor %}
                                                    <option value="__custom__"{% if isCustomRole %} selected{% endif %}>Custom role...</option>
                                                </select>
                                            </div>
                                            <div class="dealflow-contact-role-custom{% if not isCustomRole %} is-hidden{% endif %}" data-dealflow-role-custom>
                                                <div class="form-group">
                                                    <label class="sr-only" for="dealflow_contact_role_custom_{{ loop.index0 }}">Custom role</label>
                                                    <input
                                                        class="form-control"
                                                        id="dealflow_contact_role_custom_{{ loop.index0 }}"
                                                        type="text"
                                                        name="deal_contacts[{{ loop.index0 }}][label_custom]"
                                                        value="{{ isCustomRole ? row.label : '' }}"
                                                        placeholder="Enter stakeholder role"
                                                        data-dealflow-role-custom-input="true"
                                                    >
                                                </div>
                                            </div>
                                        </div>
                                        <div class="dealflow-contact-row__remove">
                                            <button class="btn btn-link text-danger" type="button" data-dealflow-remove-contact>
                                                Remove stakeholder
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            {% endfor %}
                        </div>
                    </div>
                </section>

                <section class="dealflow-entry-card">
                    <div class="dealflow-entry-card__header">
                        <div>
                            <h3 class="dealflow-entry-card__title">Deal narrative</h3>
                            <p class="dealflow-entry-card__subtitle">Capture the buyer context, the commercial motion, and the next move while everything is still fresh.</p>
                        </div>
                    </div>
                    <div class="dealflow-entry-card__body">
                        {{ form_row(form.description) }}
                    </div>
                </section>
            </div>

            {{ include('@DealFlow/Deal/_custom_fields_form.html.twig') }}
        </div>

        <div class="dealflow-entry-actions">
            <button class="btn btn-primary btn-apply" type="submit" name="deal[buttons][apply]">
                <i class="ri-check-line"></i>
                Save
            </button>
            <button class="btn btn-primary btn-save" type="submit" name="deal[buttons][save]">
                <i class="ri-save-line"></i>
                Save &amp; Close
            </button>
            {% if isModal %}
                <button class="btn btn-secondary btn-cancel" type="button" data-dismiss="modal">
                    <i class="ri-close-line"></i>
                    Cancel
                </button>
            {% else %}
                <a class="btn btn-secondary btn-cancel" href="{{ cancelUrl|default(path('mautic_dealflow_pipeline')) }}" data-toggle="ajax">
                    <i class="ri-close-line"></i>
                    Cancel
                </a>
            {% endif %}
        </div>
    </div>
    {{ form_end(form) }}

    <script id="dealflowContactRowTemplate" type="text/template">
        <div class="dealflow-contact-row" data-dealflow-contact-row>
            <div class="dealflow-contact-picker">
                <div class="dealflow-contact-picker__selection" data-dealflow-contact-selection>
                    <span class="dealflow-contact-pill">
                        <i class="ri-user-3-line"></i>
                        <span class="dealflow-contact-pill__label" data-dealflow-contact-selected-label>Selected contact</span>
                    </span>
                    <div class="dealflow-contact-picker__actions">
                        <button class="btn btn-default btn-xs" type="button" data-dealflow-change-contact>
                            Change
                        </button>
                        <button class="btn btn-link btn-xs text-danger" type="button" data-dealflow-clear-contact>
                            Clear
                        </button>
                    </div>
                </div>

                <div class="dealflow-contact-picker__lookup" data-dealflow-contact-lookup-wrap>
                    <div class="form-group">
                        <label class="control-label" for="dealflow_contact_display___INDEX__">Contact</label>
                        <input
                            type="hidden"
                            name="deal_contacts[__INDEX__][contact_name]"
                            value=""
                            data-dealflow-contact-name="true"
                        >
                        <input
                            class="form-control"
                            id="dealflow_contact_display___INDEX__"
                            type="text"
                            value=""
                            autocomplete="off"
                            placeholder="Start typing a contact name"
                            data-toggle="field-lookup"
                            data-callback="updateDealFlowEntryContactSelection"
                            data-lookup-callback="updateDealFlowEntryContactSelection"
                            data-chosen-lookup="lead:contactList"
                            data-target="undefined"
                            data-no-record-message="No matching contacts found"
                            data-dealflow-contact-lookup="true"
                        >
                        <input
                            type="hidden"
                            name="deal_contacts[__INDEX__][contact_id]"
                            value=""
                            data-dealflow-contact-id="true"
                        >
                    </div>
                </div>
            </div>

            <div class="dealflow-contact-row__secondary">
                <div class="dealflow-contact-row__role">
                    <div class="form-group">
                        <label class="control-label" for="dealflow_contact_role_select___INDEX__">Role</label>
                        <select
                            class="form-control"
                            id="dealflow_contact_role_select___INDEX__"
                            name="deal_contacts[__INDEX__][label_selection]"
                            data-dealflow-role-select="true"
                        >
                            <option value="">Select stakeholder role</option>
                            {% for role in roleSuggestions %}
                                <option value="{{ role }}">{{ role }}</option>
                            {% endfor %}
                            <option value="__custom__">Custom role...</option>
                        </select>
                    </div>
                    <div class="dealflow-contact-role-custom is-hidden" data-dealflow-role-custom>
                        <div class="form-group">
                            <label class="sr-only" for="dealflow_contact_role_custom___INDEX__">Custom role</label>
                            <input
                                class="form-control"
                                id="dealflow_contact_role_custom___INDEX__"
                                type="text"
                                name="deal_contacts[__INDEX__][label_custom]"
                                value=""
                                placeholder="Enter stakeholder role"
                                data-dealflow-role-custom-input="true"
                            >
                        </div>
                    </div>
                </div>

                <div class="dealflow-contact-row__remove">
                    <button class="btn btn-link text-danger" type="button" data-dealflow-remove-contact>
                        Remove stakeholder
                    </button>
                </div>
            </div>
        </div>
    </script>

    <script>
        (function () {
            var sourceSelect = mQuery('#{{ form.sourceSelection.vars.id }}');
            var sourceNewWrapper = mQuery('[data-dealflow-source-new]');
            var pipelineSelect = mQuery('#{{ form.pipeline.vars.id }}');
            var stageSelect = mQuery('#{{ form.stage.vars.id }}');
            var contactsContainer = mQuery('[data-dealflow-contacts]');
            var contactTemplate = mQuery('#dealflowContactRowTemplate').html();
            var nextContactIndex = contactsContainer.find('[data-dealflow-contact-row]').length;

            function updateSourceVisibility() {
                if (!sourceSelect.length || !sourceNewWrapper.length) {
                    return;
                }

                sourceNewWrapper.toggleClass('is-hidden', sourceSelect.val() !== '__new__');
            }

            function updateStageChoices() {
                if (!pipelineSelect.length || !stageSelect.length) {
                    return;
                }

                var selectedPipelineText = pipelineSelect.find('option:selected').text();
                var selectedValueStillVisible = false;

                stageSelect.find('option').each(function () {
                    var option = mQuery(this);
                    var optgroup = option.parent('optgroup');
                    var isVisible = !optgroup.length || optgroup.attr('label') === selectedPipelineText;

                    if (option.val() === '') {
                        return;
                    }

                    option.prop('disabled', !isVisible);
                    option.prop('hidden', !isVisible);

                    if (isVisible && option.is(':selected')) {
                        selectedValueStillVisible = true;
                    }
                });

                if (!selectedValueStillVisible) {
                    var firstVisibleValue = '';
                    stageSelect.find('option').each(function () {
                        var option = mQuery(this);
                        if (option.val() !== '' && !option.prop('disabled')) {
                            firstVisibleValue = option.val();

                            return false;
                        }
                    });
                    stageSelect.val(firstVisibleValue);
                }

                stageSelect.trigger('chosen:updated');
            }

            function bindContactLookup(fieldEl) {
                if (!fieldEl.length || fieldEl.data('dealflowLookupBound')) {
                    return;
                }

                var lookupElementId = fieldEl.attr('id');
                var action = fieldEl.attr('data-chosen-lookup');
                var options = {
                    limit: 20,
                    searchKey: 'lead.lead'
                };

                Mautic.activateFieldTypeahead(lookupElementId, 'undefined', options, action);
                fieldEl.data('dealflowLookupBound', true);
                fieldEl.off('change.dealflow').on('change.dealflow', function (event) {
                    var row = fieldEl.closest('[data-dealflow-contact-row]');

                    if ((event.target.value || '').trim() === '') {
                        clearContactSelection(row, false);

                        return;
                    }

                    row.find('input[data-dealflow-contact-name]').val(event.target.value);
                });
            }

            function syncContactSelectionState(row) {
                if (!row.length) {
                    return;
                }

                var lookupWrap = row.find('[data-dealflow-contact-lookup-wrap]');
                var selectionWrap = row.find('[data-dealflow-contact-selection]');
                var contactIdField = row.find('input[data-dealflow-contact-id]');
                var contactNameField = row.find('input[data-dealflow-contact-name]');
                var contactLookupField = row.find('input[data-dealflow-contact-lookup]');
                var selectedLabel = row.find('[data-dealflow-contact-selected-label]');
                var hasSelection = (contactIdField.val() || '').trim() !== '';
                var selectedName = (contactNameField.val() || '').trim();

                if (selectedName === '') {
                    selectedName = (contactLookupField.val() || '').trim();
                }

                if (hasSelection) {
                    selectedLabel.text(selectedName !== '' ? selectedName : 'Selected contact');
                    selectionWrap.addClass('is-active');
                    lookupWrap.addClass('is-hidden');
                } else {
                    selectedLabel.text('Selected contact');
                    selectionWrap.removeClass('is-active');
                    lookupWrap.removeClass('is-hidden');
                }
            }

            function syncRoleSelectionState(row) {
                if (!row.length) {
                    return;
                }

                var roleSelect = row.find('select[data-dealflow-role-select]');
                var customWrap = row.find('[data-dealflow-role-custom]');
                var customInput = row.find('input[data-dealflow-role-custom-input]');
                var isCustom = roleSelect.val() === '__custom__';

                customWrap.toggleClass('is-hidden', !isCustom);

                if (!isCustom) {
                    customInput.val('');
                }
            }

            function setContactSelection(row, contactId, contactName) {
                if (!row.length) {
                    return;
                }

                row.find('input[data-dealflow-contact-id]').val(contactId || '');
                row.find('input[data-dealflow-contact-name]').val(contactName || '');
                row.find('input[data-dealflow-contact-lookup]').val(contactName || '');
                row.find('[data-dealflow-contact-selected-label]').text(contactName || 'Selected contact');
                syncContactSelectionState(row);
            }

            function clearContactSelection(row, focusLookup) {
                if (!row.length) {
                    return;
                }

                var lookupField = row.find('input[data-dealflow-contact-lookup]');

                row.find('input[data-dealflow-contact-id]').val('');
                row.find('input[data-dealflow-contact-name]').val('');
                lookupField.val('');
                syncContactSelectionState(row);

                if (focusLookup) {
                    lookupField.trigger('focus');
                }
            }

            function bindAllContactLookups() {
                contactsContainer.find('input[data-dealflow-contact-lookup]').each(function () {
                    bindContactLookup(mQuery(this));
                });

                contactsContainer.find('[data-dealflow-contact-row]').each(function () {
                    var row = mQuery(this);

                    syncContactSelectionState(row);
                    syncRoleSelectionState(row);
                });
            }

            function ensureAtLeastOneContactRow() {
                if (!contactsContainer.find('[data-dealflow-contact-row]').length) {
                    addContactRow();
                }
            }

            function addContactRow() {
                var rowHtml = contactTemplate.replace(/__INDEX__/g, String(nextContactIndex));
                nextContactIndex += 1;
                contactsContainer.append(rowHtml);
                bindAllContactLookups();
            }

            Mautic.updateDealFlowEntryContactSelection = function (fieldId, item) {
                var fieldEl = mQuery('#' + fieldId);
                var row = fieldEl.closest('[data-dealflow-contact-row]');

                if (!row.length) {
                    return;
                }

                setContactSelection(
                    row,
                    item && item.id ? String(item.id) : '',
                    item && (item.value || item.name || item.label) ? (item.value || item.name || item.label) : ''
                );
            };

            mQuery(document).off('click.dealflowAddContact').on('click.dealflowAddContact', '[data-dealflow-add-contact]', function () {
                addContactRow();
            });

            mQuery(document).off('click.dealflowRemoveContact').on('click.dealflowRemoveContact', '[data-dealflow-remove-contact]', function () {
                mQuery(this).closest('[data-dealflow-contact-row]').remove();
                ensureAtLeastOneContactRow();
            });

            mQuery(document).off('click.dealflowChangeContact').on('click.dealflowChangeContact', '[data-dealflow-change-contact]', function () {
                clearContactSelection(mQuery(this).closest('[data-dealflow-contact-row]'), true);
            });

            mQuery(document).off('click.dealflowClearContact').on('click.dealflowClearContact', '[data-dealflow-clear-contact]', function () {
                clearContactSelection(mQuery(this).closest('[data-dealflow-contact-row]'), false);
            });

            mQuery(document).off('change.dealflowRoleSelect').on('change.dealflowRoleSelect', 'select[data-dealflow-role-select]', function () {
                syncRoleSelectionState(mQuery(this).closest('[data-dealflow-contact-row]'));
            });

            sourceSelect.off('change.dealflow').on('change.dealflow', updateSourceVisibility);
            pipelineSelect.off('change.dealflow').on('change.dealflow', updateStageChoices);

            updateSourceVisibility();
            updateStageChoices();
            bindAllContactLookups();
        })();
    </script>
{% endblock %}
