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

{% block headerTitle pageTitle %}

{% block content %}
    {% set isModal = isModal|default(false) %}
    {% set selectedFieldType = form.fieldType.vars.value|default(field.getFieldType()|default('text')) %}
    {% set isRequiredChecked = form.isRequired.vars.checked|default(false) %}

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

        .dealflow-field-entry--modal {
            border: 0;
            border-radius: var(--border-radius-md);
        }

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

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

        .dealflow-field-entry__body {
            display: flex;
            flex-direction: column;
            gap: 18px;
            padding: 24px 26px;
        }

        .dealflow-field-entry__body--modal {
            padding-top: 20px;
        }

        .dealflow-field-entry__card {
            background: var(--background);
            border: 1px solid var(--border-subtle-01);
            border-radius: var(--border-radius-md);
            overflow: visible;
        }

        .dealflow-field-entry__card-head {
            background: var(--layer-01);
            border-top-left-radius: inherit;
            border-top-right-radius: inherit;
            border-bottom: 1px solid var(--border-subtle-01);
            padding: 16px 18px 14px;
        }

        .dealflow-field-entry__card-title {
            color: var(--text-primary);
            font-size: 17px;
            font-weight: 700;
            margin: 0 0 4px;
        }

        .dealflow-field-entry__card-copy {
            color: var(--text-secondary);
            font-size: 13px;
            margin: 0;
        }

        .dealflow-field-entry__card-body {
            border-bottom-left-radius: inherit;
            border-bottom-right-radius: inherit;
            padding: 18px;
        }

        .dealflow-field-entry__hint {
            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.55;
            margin-top: 16px;
            padding: 12px 14px;
        }

        .dealflow-field-entry__actions {
            border-top: 1px solid var(--border-subtle-01);
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            padding: 18px 26px 22px;
        }

        .dealflow-field-entry__group.is-hidden {
            display: none;
        }

        .dealflow-field-entry__builder-stack {
            display: flex;
            flex-direction: column;
            gap: 18px;
        }

        .dealflow-field-entry__builder-grid {
            display: grid;
            gap: 16px;
            grid-template-columns: repeat(2, minmax(0, 1fr));
        }

        .dealflow-field-entry__builder-block {
            background: var(--layer-01);
            border: 1px solid var(--border-subtle-01);
            border-radius: var(--border-radius-sm);
            padding: 16px;
        }

        .dealflow-field-entry__builder-block--span {
            grid-column: 1 / -1;
        }

        .dealflow-field-entry__section-title {
            color: var(--text-primary);
            font-size: 14px;
            font-weight: 700;
            margin: 0 0 6px;
        }

        .dealflow-field-entry__section-copy {
            color: var(--text-secondary);
            font-size: 12px;
            line-height: 1.5;
            margin: 0 0 14px;
        }

        .dealflow-field-entry__meta {
            color: var(--text-secondary);
            font-size: 12px;
            margin-top: 8px;
        }

        .dealflow-field-entry .form-control,
        .dealflow-field-entry .chosen-container-single .chosen-single,
        .dealflow-field-entry .chosen-container-multi .chosen-choices {
            background: var(--background);
            border: 1px solid var(--border-subtle-01);
            border-radius: var(--border-radius-sm);
            box-shadow: none;
            color: var(--text-primary);
            min-height: 42px;
        }

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

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

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

        .dealflow-field-entry .form-control::placeholder {
            color: var(--text-secondary);
        }

        .dealflow-field-entry .form-control:focus,
        .dealflow-field-entry .chosen-container-active .chosen-single,
        .dealflow-field-entry .chosen-container-active .chosen-choices {
            border-color: var(--link-primary);
            box-shadow: 0 0 0 1px var(--link-primary);
        }

        .dealflow-field-entry textarea.form-control {
            min-height: 118px;
            resize: vertical;
        }

        .dealflow-field-entry__option-list {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        .dealflow-field-entry__option-row {
            align-items: center;
            display: grid;
            gap: 10px;
            grid-template-columns: 36px minmax(0, 1fr) auto;
        }

        .dealflow-field-entry__option-index {
            align-items: center;
            background: var(--layer-02);
            border: 1px solid var(--border-subtle-01);
            border-radius: 999px;
            color: var(--text-secondary);
            display: inline-flex;
            font-size: 12px;
            font-weight: 700;
            height: 32px;
            justify-content: center;
            width: 32px;
        }

        .dealflow-field-entry__option-remove {
            background: transparent;
            border: 0;
            border-radius: var(--border-radius-sm);
            color: var(--text-secondary);
            font-size: 12px;
            font-weight: 600;
            padding: 0 4px;
        }

        .dealflow-field-entry__option-remove:hover,
        .dealflow-field-entry__option-remove:focus {
            color: var(--text-primary);
            outline: none;
            text-decoration: underline;
        }

        .dealflow-field-entry__option-add {
            align-items: center;
            background: var(--layer-01);
            border: 1px dashed var(--border-subtle-01);
            border-radius: var(--border-radius-sm);
            color: var(--text-primary);
            display: inline-flex;
            font-size: 13px;
            font-weight: 600;
            gap: 8px;
            justify-content: center;
            margin-top: 12px;
            min-height: 40px;
            padding: 0 16px;
        }

        .dealflow-field-entry__option-add:hover,
        .dealflow-field-entry__option-add:focus {
            border-color: var(--link-primary);
            color: var(--link-primary);
            outline: none;
            text-decoration: none;
        }

        .dealflow-field-entry__toggle {
            background: var(--layer-01);
            border: 1px solid var(--border-subtle-01);
            border-radius: 999px;
            display: inline-flex;
            gap: 4px;
            padding: 4px;
        }

        .dealflow-field-entry__toggle-button {
            background: transparent;
            border: 0;
            border-radius: 999px;
            color: var(--text-secondary);
            font-size: 13px;
            font-weight: 700;
            min-width: 74px;
            padding: 8px 14px;
        }

        .dealflow-field-entry__toggle-button.is-active {
            background: var(--link-primary);
            color: #fff;
        }

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

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

            .dealflow-field-entry__option-row {
                grid-template-columns: 32px minmax(0, 1fr);
            }

            .dealflow-field-entry__option-remove {
                justify-self: flex-end;
                grid-column: 2;
            }
        }
    </style>

    {{ form_start(form, {'action': formAction|default(null)}) }}
    <div
        class="dealflow-field-entry{{ isModal ? ' dealflow-field-entry--modal' : '' }}"
        data-dealflow-field-builder
    >
        <div class="dealflow-field-entry__body{{ isModal ? ' dealflow-field-entry__body--modal' : '' }}">
            {% if form.vars.errors|length > 0 %}
                <div class="alert alert-danger">
                    {{ form_errors(form) }}
                </div>
            {% endif %}

            <section class="dealflow-field-entry__card">
                <div class="dealflow-field-entry__card-head">
                    <h3 class="dealflow-field-entry__card-title">Field basics</h3>
                    <p class="dealflow-field-entry__card-copy">Define the label and type first. The form will trim down to only the settings that matter for that field type.</p>
                </div>
                <div class="dealflow-field-entry__card-body">
                    <div class="row">
                        <div class="col-md-6">{{ form_row(form.label) }}</div>
                        <div class="col-md-6">{{ form_row(form.alias) }}</div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">{{ form_row(form.fieldType) }}</div>
                        <div class="col-md-6">{{ form_row(form.sortOrder) }}</div>
                    </div>
                    <div class="dealflow-field-entry__meta">
                        Leave <strong>API alias</strong> blank and Deal Flow will generate a clean key from the label when you save.
                    </div>
                </div>
            </section>

            <section class="dealflow-field-entry__card">
                <div class="dealflow-field-entry__card-head">
                    <h3 class="dealflow-field-entry__card-title">Behavior</h3>
                    <p class="dealflow-field-entry__card-copy">Control whether the field is required, visible in deal lists, and available to users right away.</p>
                </div>
                <div class="dealflow-field-entry__card-body">
                    <div class="row">
                        <div class="col-md-4">{{ form_row(form.isRequired) }}</div>
                        <div class="col-md-4">{{ form_row(form.showInList) }}</div>
                        <div class="col-md-4">{{ form_row(form.isActive) }}</div>
                    </div>
                </div>
            </section>

            <section
                class="dealflow-field-entry__card dealflow-field-entry__group"
                data-field-builder-group
                data-field-types="text,textarea,number,date,boolean,select"
            >
                <div class="dealflow-field-entry__card-head">
                    <h3 class="dealflow-field-entry__card-title">Type-specific setup</h3>
                    <p class="dealflow-field-entry__card-copy">Match the configuration to the kind of field you are creating so new deals start with clean, intentional defaults.</p>
                </div>
                <div class="dealflow-field-entry__card-body">
                    <div class="dealflow-field-entry__builder-stack">
                        <div
                            class="dealflow-field-entry__group{{ selectedFieldType != 'select' ? ' is-hidden' : '' }}"
                            data-field-builder-group
                            data-field-types="select"
                        >
                            <div class="dealflow-field-entry__builder-grid">
                                <div class="dealflow-field-entry__builder-block dealflow-field-entry__builder-block--span">
                                    <h4 class="dealflow-field-entry__section-title">Select options</h4>
                                    <p class="dealflow-field-entry__section-copy">Build the option list inline. The default picker will stay in sync as you add, remove, or rename choices.</p>

                                    <div class="dealflow-field-entry__option-list" data-option-list>
                                        {% for option in fieldBuilder.options %}
                                            <div class="dealflow-field-entry__option-row" data-option-row>
                                                <span class="dealflow-field-entry__option-index">{{ loop.index }}</span>
                                                <input
                                                    class="form-control"
                                                    type="text"
                                                    name="deal_field_builder[options][]"
                                                    value="{{ option }}"
                                                    placeholder="Option label"
                                                    data-option-input
                                                >
                                                <button class="dealflow-field-entry__option-remove" type="button" data-remove-option>
                                                    Remove
                                                </button>
                                            </div>
                                        {% endfor %}
                                    </div>

                                    <button class="dealflow-field-entry__option-add" type="button" data-add-option>
                                        Add option
                                    </button>
                                </div>

                                <div class="dealflow-field-entry__builder-block">
                                    <h4 class="dealflow-field-entry__section-title">Default value</h4>
                                    <p class="dealflow-field-entry__section-copy">Choose the option new deals should inherit first. Leave it blank if the field should start empty.</p>
                                    <label class="control-label" for="deal_field_builder_default_select_value">Default option</label>
                                    <select
                                        class="form-control"
                                        id="deal_field_builder_default_select_value"
                                        name="deal_field_builder[default_select_value]"
                                        data-default-select
                                        data-selected-value="{{ fieldBuilder.defaultSelectValue }}"
                                    >
                                        <option value="">No default option</option>
                                        {% for option in fieldBuilder.options %}
                                            {% if option is not empty %}
                                                <option value="{{ option }}"{{ fieldBuilder.defaultSelectValue == option ? ' selected' : '' }}>
                                                    {{ option }}
                                                </option>
                                            {% endif %}
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div
                            class="dealflow-field-entry__group{{ selectedFieldType != 'text' ? ' is-hidden' : '' }}"
                            data-field-builder-group
                            data-field-types="text"
                        >
                            <div class="dealflow-field-entry__builder-block">
                                <h4 class="dealflow-field-entry__section-title">Default value</h4>
                                <p class="dealflow-field-entry__section-copy">Use a short starter value when every new deal should begin with the same text.</p>
                                <label class="control-label" for="deal_field_builder_default_text_value">Default text</label>
                                <input
                                    class="form-control"
                                    id="deal_field_builder_default_text_value"
                                    name="deal_field_builder[default_text_value]"
                                    type="text"
                                    value="{{ fieldBuilder.defaultTextValue }}"
                                    placeholder="Starter value"
                                >
                            </div>
                        </div>

                        <div
                            class="dealflow-field-entry__group{{ selectedFieldType != 'textarea' ? ' is-hidden' : '' }}"
                            data-field-builder-group
                            data-field-types="textarea"
                        >
                            <div class="dealflow-field-entry__builder-block">
                                <h4 class="dealflow-field-entry__section-title">Default value</h4>
                                <p class="dealflow-field-entry__section-copy">Seed long text fields with guidance, checklist text, or a template that reps can edit.</p>
                                <label class="control-label" for="deal_field_builder_default_textarea_value">Default long text</label>
                                <textarea
                                    class="form-control"
                                    id="deal_field_builder_default_textarea_value"
                                    name="deal_field_builder[default_textarea_value]"
                                    rows="4"
                                    placeholder="Template or guidance"
                                >{{ fieldBuilder.defaultTextareaValue }}</textarea>
                            </div>
                        </div>

                        <div
                            class="dealflow-field-entry__group{{ selectedFieldType != 'number' ? ' is-hidden' : '' }}"
                            data-field-builder-group
                            data-field-types="number"
                        >
                            <div class="dealflow-field-entry__builder-block">
                                <h4 class="dealflow-field-entry__section-title">Default value</h4>
                                <p class="dealflow-field-entry__section-copy">Choose the numeric baseline new deals should inherit before a rep edits the value.</p>
                                <label class="control-label" for="deal_field_builder_default_number_value">Default number</label>
                                <input
                                    class="form-control"
                                    id="deal_field_builder_default_number_value"
                                    name="deal_field_builder[default_number_value]"
                                    type="number"
                                    step="any"
                                    value="{{ fieldBuilder.defaultNumberValue }}"
                                    placeholder="0"
                                >
                            </div>
                        </div>

                        <div
                            class="dealflow-field-entry__group{{ selectedFieldType != 'date' ? ' is-hidden' : '' }}"
                            data-field-builder-group
                            data-field-types="date"
                        >
                            <div class="dealflow-field-entry__builder-block">
                                <h4 class="dealflow-field-entry__section-title">Default value</h4>
                                <p class="dealflow-field-entry__section-copy">Pick the date new deals should start with if there is a standard baseline.</p>
                                <label class="control-label" for="deal_field_builder_default_date_value">Default date</label>
                                <input
                                    class="form-control"
                                    id="deal_field_builder_default_date_value"
                                    name="deal_field_builder[default_date_value]"
                                    type="date"
                                    value="{{ fieldBuilder.defaultDateValue }}"
                                >
                            </div>
                        </div>

                        <div
                            class="dealflow-field-entry__group{{ selectedFieldType != 'boolean' or not isRequiredChecked ? ' is-hidden' : '' }}"
                            data-field-builder-group
                            data-field-types="boolean"
                            data-required-only="true"
                        >
                            <div class="dealflow-field-entry__builder-block">
                                <h4 class="dealflow-field-entry__section-title">Default state</h4>
                                <p class="dealflow-field-entry__section-copy">Because this yes/no field is required, every new deal needs a starting state right away.</p>
                                <input
                                    data-boolean-input
                                    name="deal_field_builder[default_boolean_value]"
                                    type="hidden"
                                    value="{{ fieldBuilder.defaultBooleanValue ? '1' : '0' }}"
                                >
                                <div aria-label="Default boolean state" class="dealflow-field-entry__toggle" role="group">
                                    <button
                                        class="dealflow-field-entry__toggle-button{{ not fieldBuilder.defaultBooleanValue ? ' is-active' : '' }}"
                                        type="button"
                                        data-boolean-value="0"
                                    >
                                        Off
                                    </button>
                                    <button
                                        class="dealflow-field-entry__toggle-button{{ fieldBuilder.defaultBooleanValue ? ' is-active' : '' }}"
                                        type="button"
                                        data-boolean-value="1"
                                    >
                                        On
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>

        <div class="dealflow-field-entry__actions">
            <button class="btn btn-primary" type="submit">Save Deal Field</button>
            {% if isModal %}
                <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
            {% else %}
                <a class="btn btn-secondary" href="{{ cancelUrl }}" data-toggle="ajax">Cancel</a>
            {% endif %}
            {% if field is defined and field.getId() and not isModal %}
                <a class="btn btn-danger" href="{{ path('mautic_dealflow_field_delete', {'objectId': field.getId()}) }}">Delete Deal Field</a>
            {% endif %}
        </div>
    </div>
    {{ form_end(form) }}

    <script>
        (function () {
            function getCurrentType(root) {
                var fieldType = root.querySelector('#deal_field_fieldType');

                return fieldType ? fieldType.value : '';
            }

            function isRequiredChecked(root) {
                var isRequired = root.querySelector('#deal_field_isRequired');

                return !!(isRequired && isRequired.checked);
            }

            function setGroupDisabled(group, disabled) {
                group.querySelectorAll('input, textarea, select, button').forEach(function (input) {
                    input.disabled = disabled;
                });
            }

            function getOptionValues(root) {
                var values = [];

                root.querySelectorAll('[data-option-input]').forEach(function (input) {
                    var value = input.value.trim();

                    if (!value || values.indexOf(value) !== -1) {
                        return;
                    }

                    values.push(value);
                });

                return values;
            }

            function ensureOptionRow(root) {
                var list = root.querySelector('[data-option-list]');

                if (!list || list.querySelector('[data-option-row]')) {
                    return;
                }

                appendOptionRow(root, '');
            }

            function syncOptionIndexes(root) {
                root.querySelectorAll('[data-option-row]').forEach(function (row, index) {
                    var badge = row.querySelector('.dealflow-field-entry__option-index');

                    if (badge) {
                        badge.textContent = String(index + 1);
                    }
                });
            }

            function syncDefaultSelect(root) {
                var select = root.querySelector('[data-default-select]');

                if (!select) {
                    return;
                }

                var selectedValue = select.value || select.getAttribute('data-selected-value') || '';
                var optionValues = getOptionValues(root);

                select.innerHTML = '';

                var emptyOption = document.createElement('option');
                emptyOption.value = '';
                emptyOption.textContent = 'No default option';
                select.appendChild(emptyOption);

                optionValues.forEach(function (value) {
                    var option = document.createElement('option');
                    option.value = value;
                    option.textContent = value;
                    select.appendChild(option);
                });

                if (optionValues.indexOf(selectedValue) !== -1) {
                    select.value = selectedValue;
                } else {
                    select.value = '';
                }

                select.setAttribute('data-selected-value', select.value);

                // Trigger Chosen to re-read the select options after innerHTML replacement
                if (typeof mQuery !== 'undefined') {
                    mQuery(select).trigger('chosen:updated');
                }
            }

            function appendOptionRow(root, value) {
                var list = root.querySelector('[data-option-list]');

                if (!list) {
                    return;
                }

                var row = document.createElement('div');
                row.className = 'dealflow-field-entry__option-row';
                row.setAttribute('data-option-row', '');
                row.innerHTML = ''
                    + '<span class="dealflow-field-entry__option-index"></span>'
                    + '<input class="form-control" type="text" name="deal_field_builder[options][]" placeholder="Option label" data-option-input>'
                    + '<button class="dealflow-field-entry__option-remove" type="button" data-remove-option>Remove</button>';

                row.querySelector('[data-option-input]').value = value || '';
                list.appendChild(row);
                syncOptionIndexes(root);
                syncDefaultSelect(root);
            }

            function syncBooleanToggle(root) {
                var hiddenInput = root.querySelector('[data-boolean-input]');

                if (!hiddenInput) {
                    return;
                }

                root.querySelectorAll('[data-boolean-value]').forEach(function (button) {
                    button.classList.toggle('is-active', button.getAttribute('data-boolean-value') === hiddenInput.value);
                });
            }

            function syncDealFieldBuilder(root) {
                if (!root) {
                    return;
                }

                var currentType = getCurrentType(root);
                var requiredChecked = isRequiredChecked(root);
                var groups = root.querySelectorAll('[data-field-builder-group]');

                if (!currentType || !groups.length) {
                    return;
                }

                groups.forEach(function (group) {
                    var typeOnly = (group.getAttribute('data-field-types') || '').split(',').map(function (value) {
                        return value.trim();
                    }).filter(Boolean);
                    var requiredOnly = group.getAttribute('data-required-only');
                    var visible = !typeOnly.length || typeOnly.indexOf(currentType) !== -1;

                    if (visible && requiredOnly === 'true' && !requiredChecked) {
                        visible = false;
                    }

                    group.classList.toggle('is-hidden', !visible);
                    setGroupDisabled(group, !visible);
                });

                ensureOptionRow(root);
                syncOptionIndexes(root);
                syncDefaultSelect(root);
                syncBooleanToggle(root);
            }

            function bootDealFieldBuilder(context) {
                var roots = (context || document).querySelectorAll('[data-dealflow-field-builder]');

                roots.forEach(function (root) {
                    if (root.dataset.dealflowFieldBooted === '1') {
                        syncDealFieldBuilder(root);
                        return;
                    }

                    root.dataset.dealflowFieldBooted = '1';

                    var fieldType = root.querySelector('#deal_field_fieldType');
                    var isRequired = root.querySelector('#deal_field_isRequired');
                    var addOption = root.querySelector('[data-add-option]');
                    var optionList = root.querySelector('[data-option-list]');
                    var defaultSelect = root.querySelector('[data-default-select]');

                    if (fieldType) {
                        mQuery('#' + fieldType.id).on('change', function () {
                            syncDealFieldBuilder(root);
                        });
                    }

                    if (isRequired) {
                        mQuery('#' + isRequired.id).on('change', function () {
                            syncDealFieldBuilder(root);
                        });
                    }

                    if (addOption) {
                        addOption.addEventListener('click', function () {
                            appendOptionRow(root, '');

                            var optionRows = root.querySelectorAll('[data-option-row]');
                            if (optionRows.length) {
                                optionRows[optionRows.length - 1].querySelector('[data-option-input]').focus();
                            }
                        });
                    }

                    if (optionList) {
                        optionList.addEventListener('input', function (event) {
                            if (event.target && event.target.matches('[data-option-input]')) {
                                syncDefaultSelect(root);
                            }
                        });

                        optionList.addEventListener('click', function (event) {
                            var button = event.target.closest('[data-remove-option]');

                            if (!button) {
                                return;
                            }

                            var row = button.closest('[data-option-row]');
                            if (row) {
                                row.remove();
                                ensureOptionRow(root);
                                syncOptionIndexes(root);
                                syncDefaultSelect(root);
                            }
                        });
                    }

                    root.querySelectorAll('[data-boolean-value]').forEach(function (button) {
                        button.addEventListener('click', function () {
                            var hiddenInput = root.querySelector('[data-boolean-input]');

                            if (!hiddenInput) {
                                return;
                            }

                            hiddenInput.value = button.getAttribute('data-boolean-value');
                            syncBooleanToggle(root);
                        });
                    });

                    if (defaultSelect) {
                        mQuery('#' + defaultSelect.id).on('change', function () {
                            defaultSelect.setAttribute('data-selected-value', defaultSelect.value);
                        });
                    }

                    var formEl = root.closest('form');
                    if (formEl) {
                        formEl.addEventListener('submit', function (event) {
                            var label = root.querySelector('#deal_field_label');
                            if (label && label.value.trim() === '') {
                                event.preventDefault();
                                label.focus();
                                var group = label.closest('.form-group');
                                if (group) {
                                    group.classList.add('has-error');
                                }
                            }
                        });
                    }

                    syncDealFieldBuilder(root);
                });
            }

            bootDealFieldBuilder(document);
        })();
    </script>
{% endblock %}
