{% if widgetId is defined and widgetId %}
<style>
.dealflow-config-trigger{flex-shrink:0;display:flex;align-items:center;gap:4px;cursor:pointer;font-size:11px;color:var(--text-secondary,#999);opacity:0.6;transition:opacity 0.15s;line-height:1;padding:4px 0;margin-top:auto;}
.dealflow-config-trigger:hover{opacity:1;color:var(--brand-primary,#4e79a7);}
.dealflow-config-overlay{display:none;position:absolute;inset:0;z-index:10;background:rgba(255,255,255,0.97);border-radius:4px;padding:16px;flex-direction:column;gap:12px;font-size:13px;}
.dealflow-config-overlay.active{display:flex;}
.dealflow-config-overlay label{display:block;font-weight:600;margin-bottom:4px;font-size:12px;color:var(--text-secondary,#666);text-transform:uppercase;letter-spacing:0.3px;}
.dealflow-config-overlay select,.dealflow-config-overlay input{width:100%;padding:6px 8px;border:1px solid var(--border-subtle-01,#ddd);border-radius:4px;font-size:13px;background:#fff;}
.dealflow-config-overlay select:focus,.dealflow-config-overlay input:focus{outline:none;border-color:var(--brand-primary,#4e79a7);box-shadow:0 0 0 2px rgba(78,121,167,0.15);}
.dealflow-config-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:auto;padding-top:8px;border-top:1px solid var(--border-subtle-01,#eee);}
.dealflow-config-actions button{padding:5px 14px;border-radius:4px;font-size:12px;font-weight:600;cursor:pointer;border:1px solid transparent;}
.dealflow-config-actions .btn-save{background:var(--brand-primary,#4e79a7);color:#fff;border-color:var(--brand-primary,#4e79a7);}
.dealflow-config-actions .btn-save:hover{opacity:0.9;}
.dealflow-config-actions .btn-cancel{background:transparent;color:var(--text-secondary,#666);border-color:var(--border-subtle-01,#ddd);}
.dealflow-config-actions .btn-cancel:hover{background:var(--border-subtle-01,#eee);}
.dealflow-config-title{font-size:14px;font-weight:700;margin-bottom:4px;}
</style>
<div class="dealflow-config-trigger" data-config-toggle="dealflow-config-{{ widgetId }}" title="Configure widget"><span style="font-size:13px;">&#9881;</span> Configure</div>
<div class="dealflow-config-overlay" id="dealflow-config-{{ widgetId }}">
    <div class="dealflow-config-title">Widget Settings</div>
    {% if pipelines is defined and pipelines is not empty %}
    <div>
        <label for="dealflow-pipeline-{{ widgetId }}">Pipeline</label>
        <select id="dealflow-pipeline-{{ widgetId }}" data-param="pipeline_id">
            <option value="">Default pipeline</option>
            {% for pipeline in pipelines %}
                <option value="{{ pipeline.id }}"{% if currentPipelineId is defined and currentPipelineId == pipeline.id %} selected{% endif %}>{{ pipeline.name|e }}</option>
            {% endfor %}
        </select>
    </div>
    {% endif %}
    {% if showDateRange is defined and showDateRange %}
    <div>
        <label for="dealflow-weeks-{{ widgetId }}">Time Range</label>
        <select id="dealflow-weeks-{{ widgetId }}" data-param="weeks">
            <option value="4"{% if currentWeeks is defined and currentWeeks == 4 %} selected{% endif %}>30 days (4 weeks)</option>
            <option value="8"{% if currentWeeks is defined and currentWeeks == 8 %} selected{% endif %}>60 days (8 weeks)</option>
            <option value="13"{% if currentWeeks is defined and currentWeeks == 13 or currentWeeks is not defined %} selected{% endif %}>90 days (13 weeks)</option>
            <option value="26"{% if currentWeeks is defined and currentWeeks == 26 %} selected{% endif %}>6 months (26 weeks)</option>
        </select>
    </div>
    {% endif %}
    <div class="dealflow-config-actions">
        <button type="button" class="btn-cancel" data-config-cancel="dealflow-config-{{ widgetId }}">Cancel</button>
        <button type="button" class="btn-save" data-config-save="{{ widgetId }}">Save</button>
    </div>
</div>
<script>
(function(){
    var overlay = document.getElementById('dealflow-config-{{ widgetId }}');
    if (!overlay) return;
    var gear = overlay.parentNode.querySelector('[data-config-toggle="dealflow-config-{{ widgetId }}"]');

    gear.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        overlay.classList.add('active');
    });

    overlay.querySelector('[data-config-cancel]').addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        overlay.classList.remove('active');
    });

    overlay.querySelector('[data-config-save]').addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var btn = this;
        btn.disabled = true;
        btn.textContent = 'Saving...';

        var params = {};
        overlay.querySelectorAll('[data-param]').forEach(function(el) {
            params[el.getAttribute('data-param')] = el.value;
        });

        var formData = new FormData();
        formData.append('widgetId', '{{ widgetId }}');
        formData.append('_token', '{{ csrf_token('dealflow_widget_config_' ~ widgetId) }}');
        for (var key in params) {
            formData.append('params[' + key + ']', params[key]);
        }

        fetch('{{ path("mautic_dealflow_widget_config") }}', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-Token': mauticAjaxCsrf
            }
        })
        .then(function(r) {
            if (!r.ok) throw new Error('HTTP ' + r.status);
            return r.json();
        })
        .then(function(data) {
            if (data.success) {
                window.location.reload();
            } else if (data.flashes) {
                alert('Failed to save: CSRF error — please reload the page and try again.');
                btn.disabled = false;
                btn.textContent = 'Save';
            } else {
                alert('Failed to save: ' + (data.error || 'Unknown error'));
                btn.disabled = false;
                btn.textContent = 'Save';
            }
        })
        .catch(function(err) {
            alert('Failed to save widget config: ' + err.message);
            btn.disabled = false;
            btn.textContent = 'Save';
        });
    });
})();
</script>
{% endif %}
