/**
 * Deal Flow — Deal Form JavaScript
 *
 * Extracted from form.html.twig inline <script> blocks.
 * Requires window.DealFlowConfig to be set by the Twig template with:
 *   - sourceSelectId:  DOM ID for the source selection dropdown
 *   - pipelineSelectId: DOM ID for the pipeline dropdown
 *   - stageSelectId:   DOM ID for the stage dropdown
 *   - roleSuggestions: Array of role suggestion strings (for the template)
 *
 * Also requires mQuery (Mautic jQuery) and Mautic global.
 */
(function () {
    'use strict';

    var config = window.DealFlowConfig || {};
    var sourceSelect = mQuery('#' + config.sourceSelectId);
    var sourceNewWrapper = mQuery('[data-dealflow-source-new]');
    var pipelineSelect = mQuery('#' + config.pipelineSelectId);
    var stageSelect = mQuery('#' + config.stageSelectId);
    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();
})();
