{% macro render_setting(setting, id_prefix="") %}
    {% set setting_id = (id_prefix ~ "-" if id_prefix else "") ~ setting.key|replace(".", "-") %}

    <div class="ldr-settings-item form-group" data-key="{{ setting.key }}">
        <div class="ldr-settings-item-header">
            <label for="{{ setting_id }}">{{ setting.name }}</label>
            {% if setting.description %}
                <span class="ldr-settings-tooltip" title="{{ setting.description }}">
                    <i class="fas fa-info-circle"></i>
                </span>
            {% endif %}
        </div>

        {% if setting.ui_element == "textarea" %}
            {# Check if this is JSON content that should be expanded into controls #}
            {% if setting.value is mapping or (setting.value is string and (setting.value.startswith('{') and setting.value.endswith('}'))) %}
                <div class="ldr-json-expanded-controls">
                    {% if setting.value is string %}
                        {% set json_value = setting.value|tojson %}
                    {% else %}
                        {% set json_value = setting.value %}
                    {% endif %}

                    {# Store the original JSON in a hidden field #}
                    <input type="hidden" id="{{ setting_id }}_original" name="{{ setting.key }}_original" value="{{ setting.value|tojson }}">

                    {# Create individual form controls for each JSON property #}
                    <div class="ldr-json-property-controls">
                        {% for key, value in json_value.items() %}
                            <div class="ldr-json-property-item">
                                <label for="{{ setting_id }}_{{ key }}">{{ key|replace("_", " ")|title }}</label>

                                {% if value is boolean %}
                                    <div class="ldr-checkbox-label">
                                        <!-- Hidden input ensures unchecked state is submitted -->
                                        <input type="hidden"
                                               name="{{ setting.key }}_{{ key }}"
                                               id="{{ setting_id }}_{{ key }}_hidden_fallback"
                                               value="false"
                                               class="ldr-checkbox-hidden-fallback">

                                        <!-- Actual checkbox overrides hidden input when checked -->
                                        <input type="checkbox"
                                               id="{{ setting_id }}_{{ key }}"
                                               name="{{ setting.key }}_{{ key }}"
                                               value="true"
                                               class="ldr-json-property-control ldr-settings-checkbox"
                                               data-property="{{ key }}"
                                               data-parent-key="{{ setting.key }}"
                                               data-hidden-fallback="{{ setting_id }}_{{ key }}_hidden_fallback"
                                               {% if value %}checked{% endif %}
                                               {% if not setting.editable %}disabled{% endif %}>
                                        <span class="ldr-checkbox-text">{{ key|replace("_", " ")|title }}</span>
                                    </div>
                                {% elif value is number %}
                                    <input type="number"
                                           id="{{ setting_id }}_{{ key }}"
                                           name="{{ setting.key }}_{{ key }}"
                                           class="ldr-settings-input ldr-form-control ldr-json-property-control"
                                           data-property="{{ key }}"
                                           data-parent-key="{{ setting.key }}"
                                           value="{{ value }}"
                                           {% if not setting.editable %}disabled{% endif %}>
                                {% elif value is string and value in ["ITERATION", "NONE"] %}
                                    <select id="{{ setting_id }}_{{ key }}"
                                            name="{{ setting.key }}_{{ key }}"
                                            class="ldr-settings-select ldr-form-control ldr-json-property-control"
                                            data-property="{{ key }}"
                                            data-parent-key="{{ setting.key }}"
                                            {% if not setting.editable %}disabled{% endif %}>
                                        <option value="ITERATION" {% if value == "ITERATION" %}selected{% endif %}>Iteration</option>
                                        <option value="NONE" {% if value == "NONE" %}selected{% endif %}>None</option>
                                    </select>
                                {% else %}
                                    <input type="text"
                                           id="{{ setting_id }}_{{ key }}"
                                           name="{{ setting.key }}_{{ key }}"
                                           class="ldr-settings-input ldr-form-control ldr-json-property-control"
                                           data-property="{{ key }}"
                                           data-parent-key="{{ setting.key }}"
                                           value="{{ value }}"
                                           {% if not setting.editable %}disabled{% endif %}>
                                {% endif %}

                                <div class="ldr-input-help">{{ key|replace("_", " ")|title }}</div>
                            </div>
                        {% endfor %}
                    </div>
                </div>
            {% else %}
                <textarea
                    id="{{ setting_id }}"
                    name="{{ setting.key }}"
                    class="ldr-settings-textarea ldr-form-control"
                    {% if not setting.editable %}disabled{% endif %}
                >{{ setting.value if setting.value is not none else "" }}</textarea>
            {% endif %}

        {% elif setting.ui_element == "select" %}
            {% if setting.key == "llm.provider" %}
                {% from "components/custom_dropdown.html" import render_dropdown %}
                {{ render_dropdown(
                    input_id=setting.key,
                    dropdown_id=setting_id + "-dropdown",
                    placeholder="Select a provider",
                    label=None,
                    help_text=setting.description if setting.description else None,
                    allow_custom=False,
                    show_refresh=True,
                    data_setting_key=setting.key
                ) }}
            {% else %}
                <select
                    id="{{ setting_id }}"
                    name="{{ setting.key }}"
                    class="ldr-settings-select ldr-form-control"
                    {% if not setting.editable %}disabled{% endif %}
                >
                    {% for option in setting.options %}
                        <option
                            value="{{ option.value }}"
                            {% if option.value == setting.value %}selected{% endif %}
                        >
                            {{ option.label if option.label else option.value }}
                        </option>
                    {% endfor %}
                </select>
            {% endif %}

        {% elif setting.ui_element == "checkbox" %}
            <div class="ldr-checkbox-label">
                <!-- Hidden input ensures unchecked state is submitted -->
                <input type="hidden"
                       name="{{ setting.key }}"
                       id="{{ setting_id }}_hidden_fallback"
                       value="false"
                       class="ldr-checkbox-hidden-fallback">

                <!-- Actual checkbox overrides hidden input when checked -->
                <input type="checkbox"
                       id="{{ setting_id }}"
                       name="{{ setting.key }}"
                       value="true"
                       {% if setting.value == true or setting.value == "true" %}checked{% endif %}
                       {% if not setting.editable %}disabled{% endif %}
                       class="ldr-settings-checkbox"
                       data-hidden-fallback="{{ setting_id }}_hidden_fallback">
                <span class="ldr-checkbox-text">{{ setting.name }}</span>
            </div>

        {% elif setting.ui_element == "slider" or setting.ui_element == "range" %}
            {% set min_value = setting.min_value if setting.min_value is not none else 0 %}
            {% set max_value = setting.max_value if setting.max_value is not none else 100 %}
            {% set step = setting.step if setting.step is not none else 1 %}

            <div class="ldr-settings-range-container">
                <input
                    type="range"
                    id="{{ setting_id }}"
                    name="{{ setting.key }}"
                    class="ldr-settings-range ldr-form-control"
                    value="{{ setting.value if setting.value is not none else min_value }}"
                    min="{{ min_value }}"
                    max="{{ max_value }}"
                    step="{{ step }}"
                    {% if not setting.editable %}disabled{% endif %}
                >
                <span class="ldr-settings-range-value" id="{{ setting_id }}-value">{{ setting.value if setting.value is not none else min_value }}</span>
            </div>

        {% elif setting.ui_element == "number" %}
            {% set min_value = setting.min_value if setting.min_value is not none else "" %}
            {% set max_value = setting.max_value if setting.max_value is not none else "" %}
            {% set step = setting.step if setting.step is not none else 1 %}

            <input
                type="number"
                id="{{ setting_id }}"
                name="{{ setting.key }}"
                class="ldr-settings-input ldr-form-control"
                value="{{ setting.value if setting.value is not none else '' }}"
                min="{{ min_value }}"
                max="{{ max_value }}"
                step="{{ step }}"
                {% if not setting.editable %}disabled{% endif %}
            >

        {% elif setting.ui_element == "password" %}
            <input
                type="password"
                id="{{ setting_id }}"
                name="{{ setting.key }}"
                class="ldr-settings-input ldr-form-control"
                value="{{ setting.value if setting.value is not none else '' }}"
                {% if not setting.editable %}disabled{% endif %}
            >

        {% elif setting.key == "llm.model" or setting.key == "search.tool" %}
            {% from "components/custom_dropdown.html" import render_dropdown %}
            {{ render_dropdown(
                input_id=setting.key,
                dropdown_id=setting_id + "-dropdown",
                placeholder="Select or enter a value",
                label=None,
                help_text=setting.description if setting.description else None,
                allow_custom=setting.key == "llm.model",
                show_refresh=True,
                refresh_aria_label="Refresh model list" if setting.key == "llm.model" else "Refresh search engine list",
                data_setting_key=setting.key
            ) }}

        {% else %}
            {% if setting.value is mapping or (setting.value is string and (setting.value.startswith('{') and setting.value.endswith('}'))) %}
                <div class="ldr-json-expanded-controls">
                    {% if setting.value is string %}
                        {% set json_value = setting.value|tojson %}
                    {% else %}
                        {% set json_value = setting.value %}
                    {% endif %}

                    {# Store the original JSON in a hidden field #}
                    <input type="hidden" id="{{ setting_id }}_original" name="{{ setting.key }}_original" value="{{ setting.value|tojson }}">

                    {# Create individual form controls for each JSON property #}
                    <div class="ldr-json-property-controls">
                        {% for key, value in json_value.items() %}
                            <div class="ldr-json-property-item">
                                <label for="{{ setting_id }}_{{ key }}">{{ key|replace("_", " ")|title }}</label>

                                {% if value is boolean %}
                                    <div class="ldr-checkbox-label">
                                        <!-- Hidden input ensures unchecked state is submitted -->
                                        <input type="hidden"
                                               name="{{ setting.key }}_{{ key }}"
                                               id="{{ setting_id }}_{{ key }}_hidden_fallback"
                                               value="false"
                                               class="ldr-checkbox-hidden-fallback">

                                        <!-- Actual checkbox overrides hidden input when checked -->
                                        <input type="checkbox"
                                               id="{{ setting_id }}_{{ key }}"
                                               name="{{ setting.key }}_{{ key }}"
                                               value="true"
                                               class="ldr-json-property-control ldr-settings-checkbox"
                                               data-property="{{ key }}"
                                               data-parent-key="{{ setting.key }}"
                                               data-hidden-fallback="{{ setting_id }}_{{ key }}_hidden_fallback"
                                               {% if value %}checked{% endif %}
                                               {% if not setting.editable %}disabled{% endif %}>
                                        <span class="ldr-checkbox-text">{{ key|replace("_", " ")|title }}</span>
                                    </div>
                                {% elif value is number %}
                                    <input type="number"
                                           id="{{ setting_id }}_{{ key }}"
                                           name="{{ setting.key }}_{{ key }}"
                                           class="ldr-settings-input ldr-form-control ldr-json-property-control"
                                           data-property="{{ key }}"
                                           data-parent-key="{{ setting.key }}"
                                           value="{{ value }}"
                                           {% if not setting.editable %}disabled{% endif %}>
                                {% else %}
                                    <input type="text"
                                           id="{{ setting_id }}_{{ key }}"
                                           name="{{ setting.key }}_{{ key }}"
                                           class="ldr-settings-input ldr-form-control ldr-json-property-control"
                                           data-property="{{ key }}"
                                           data-parent-key="{{ setting.key }}"
                                           value="{{ value }}"
                                           {% if not setting.editable %}disabled{% endif %}>
                                {% endif %}

                                <div class="ldr-input-help">{{ key|replace("_", " ")|title }}</div>
                            </div>
                        {% endfor %}
                    </div>
                </div>
            {% else %}
                <input
                    type="text"
                    id="{{ setting_id }}"
                    name="{{ setting.key }}"
                    class="ldr-settings-input ldr-form-control"
                    value="{{ setting.value if setting.value is not none else '' }}"
                    {% if not setting.editable %}disabled{% endif %}
                >
            {% endif %}
        {% endif %}

        {% if setting.description and setting.key != "llm.model" and setting.key != "search.tool" and setting.key != "llm.provider" %}
            <div class="ldr-input-help">{{ setting.description }}</div>
        {% endif %}

        {% if setting.key == "notifications.service_url" %}
            <div class="ldr-settings-test-button-container">
                <button type="button"
                        id="test-notification-button"
                        class="btn btn-secondary btn-sm"
                        {% if not setting.value or setting.value.strip() == "" %}disabled{% endif %}>
                    <i class="fas fa-paper-plane"></i> Test Notification
                </button>
                <div id="test-notification-result" class="ldr-test-result" style="display: none;"></div>
            </div>
        {% endif %}
    </div>
{% endmacro %}

{% macro render_settings_section(section_title, section_id, settings, form_id='settings-form') %}
    <div class="ldr-settings-section">
        <div class="ldr-settings-section-header" data-target="{{ section_id }}">
            <div class="ldr-settings-section-title">
                {{ section_title }}
            </div>
            <div class="ldr-settings-toggle-icon">
                <i class="fas fa-chevron-down"></i>
            </div>
        </div>
        <div id="{{ section_id }}" class="ldr-settings-section-body">
            {% for setting in settings %}
                {{ render_setting(setting, form_id) }}
            {% endfor %}
        </div>
    </div>
{% endmacro %}

{% macro render_settings_form(settings_by_category, form_id, form_action) %}
    <form id="{{ form_id }}" action="{{ form_action }}" method="POST" class="ldr-settings-form">
        {% for category, settings in settings_by_category.items() %}
            {{ render_settings_section(category, category|lower|replace(' ', '-'), settings, form_id) }}
        {% endfor %}

        <div class="ldr-form-actions">
            <button type="reset" class="btn ldr-btn-outline">
                <i class="fas fa-undo"></i> Reset Changes
            </button>
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-save"></i> Save Changes
            </button>
        </div>
    </form>
{% endmacro %}
