{% load crispy_forms_tags %}
<div id="primary-answer-container">
    <form hx-post="{% url 'anatomy:primary_answer_htmx' pk=question.pk %}" hx-target="#primary-answer-container" hx-swap="outerHTML">
        {% csrf_token %}
        <div class="mb-2">
            <label for="id_existing_answer" class="form-label">Select existing answer</label>
            <select name="existing_answer" id="id_existing_answer" class="form-select">
                {% for val, text in form.existing_answer.field.choices %}
                    <option value="{{ val }}" {% if val == form.initial.existing_answer %}selected{% endif %}>{{ text }}</option>
                {% endfor %}
            </select>
        </div>

        <div class="mb-2">
            <label for="id_new_answer" class="form-label">Or add a new primary answer</label>
            <textarea name="new_answer" id="id_new_answer" class="form-control" rows="3"></textarea>

            <script>
                (function(){
                    const sel = document.getElementById('id_existing_answer');
                    const ta = document.getElementById('id_new_answer');
                    if(!sel || !ta) return;

                    function update() {
                        try {
                            if (ta.value && ta.value.trim().length > 0) {
                                sel.disabled = true;
                            } else {
                                sel.disabled = false;
                            }
                        } catch(e) {
                // ignore
                        }
                    }

        // initial state
                    update();

        // listeners
                    sel.addEventListener('change', function(){
                        if(this.value && this.value !== '') {
                            ta.disabled = true;
                        } else {
                            ta.disabled = false;
                        }
                    });

                    ta.addEventListener('input', update);
                })();
            </script>
        </div>

        <div class="d-flex gap-2">
            <button class="btn btn-primary btn-sm" type="submit">Save primary answer</button>
            <button class="btn btn-secondary btn-sm" type="button" hx-get="{% url 'anatomy:primary_answer_htmx' pk=question.pk %}?cancel=1" hx-target="#primary-answer-container" hx-swap="outerHTML">Cancel</button>
        </div>
    </form>
</div>
