{{ component('js_localize', keys="common.delete,admin.admin.ai.prompt_engineering.empty, common.confirm, admin.admin.ai.prompt_engineering.changes_saved, common.ai.prompt.validation.more_than") }}

<button type="button" class="btn btn-link position-relative" data-toggle="modal" data-target="#modal-{{module}}" aria-label="{{ lmsg('admin.admin.ai.prompt_engineering.title', module_label) }}">
    <ion-icon name="create-outline" aria-hidden="true"></ion-icon>
    <span class="js-instruction-badge position-absolute badge badge-pill badge-primary ai-custom-instructions-count {{ prompts|length == 0 ? 'd-none' : '' }}" >
        {{ prompts|length }}
    </span>
</button>

<div class="modal fade" id="modal-{{ module }}" tabindex="-1" aria-hidden="true" aria-labelledby="custom-prompt-modal-title">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header border-0 pb-0">
                <img src="/assets/icons/ai-response-outline.svg" width="30" height="30" />
                <h5 id="custom-prompt-modal-title" class="modal-title font-weight-bold text-capitalize ml-2">
                    {{ lmsg('admin.admin.ai.prompt_engineering.title', module_label) }}
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <ion-icon name="close" aria-hidden="true"></ion-icon>
                </button>
            </div>

            <div class="modal-body p-4">
                <p class="text-muted mb-4">
                    {{ lmsg('admin.admin.ai.prompt_engineering.info') }}
                </p>

                <section class="mb-4">
                    <h6 class="font-weight-bold mb-2 small text-uppercase text-muted">
                        {{ lmsg('admin.ai.prompt.suggestions_title') }}
                    </h6>
                    <div class="d-flex flex-wrap">
                    {% set suggestionType = module == 'image' ? 'image' : 'text' %}
                        {% for suggestion in instructionSuggestions[suggestionType] %}
                            <button type="button" 
                                    class="btn btn-secondary btn-sm mb-2 mr-2 js-suggestion" 
                                    data-prompt="{{ suggestion.prompt }}">
                                {{ suggestion.label }}
                            </button>
                        {% endfor %}
                    </div>
                </section>

                <div>
                    <h6 class="font-weight-bold mb-3">
                        {{ lmsg('admin.admin.ai.prompt_engineering.instructions') }}
                    </h6>
                    <div class="list-group list-group-flush border-top js-prompt-list"></div>

                        <div class="js-prompt-field-wrapper d-none mt-3 p-3 bg-light rounded">
                            <div class="row no-gutters align-items-start">
                                <div class="col-12 col-md-8 mr-md-2">
                                    <input type="text" class="form-control js-prompt-input" name="prompt_input" placeholder="{{ lmsg('admin.admin.ai.prompt_engineering.enter_instruction') }}" minlength="3">
                                    <div class="invalid-feedback">{{ lmsg('common.ai.prompt.validation.more_than', 3) }}</div>
                                </div>
                                <div class="col mt-2 mt-md-0">
                                    <div class="d-flex">
                                        <button type="button" class="btn btn-primary btn-block mt-0 mr-2 js-save-prompt">
                                            {{ lmsg('admin.admin.ai.prompt_engineering.save') }}
                                        </button>
                                        <button type="button" class="btn btn-secondary btn-block mt-0 js-cancel-prompt">
                                            {{ lmsg('admin.admin.ai.prompt_engineering.cancel') }}
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>


                    <div class="d-flex align-items-center justify-content-between">
                        <button type="button" class="btn btn-secondary btn-sm mt-3 js-add-prompt">
                            <ion-icon name="add-outline" class="mr-1"></ion-icon>
                            {{ lmsg('admin.admin.ai.prompt_engineering.add_instruction') }}
                        </button>

                        <small class="text-muted">
                            <span class="js-instruction-count">{{ prompts|length }}</span>/{{ maxInstructions }}
                        </small>
                    </div>
                </div>
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">
                    {{ lmsg('admin.admin.ai.prompt_engineering.cancel') }}
                </button>
                <button type="button" class="btn btn-primary js-final-save">
                    <span class="spinner-border spinner-border-sm d-none js-save-spinner" role="status"></span>
                    {{ lmsg('admin.admin.ai.prompt_engineering.save_changes') }}
                </button>
            </div>
        </div>
    </div>
</div>

<script id="list-item-template" type="text/template">
    {% verbatim %}
        <div class="list-group-item d-flex align-items-center px-0 border-bottom">
            <div class="pr-2 d-flex align-items-center">
                <ion-icon name="checkmark-circle" class="text-primary"></ion-icon>
            </div>
            
            <div class="flex-grow-1 px-2">
                <p class="mb-0 small text-dark">{{ text }}</p>
            </div>
            
            <div class="d-flex">
                <button type="button" class="btn btn-link p-1 js-edit" data-index="{{ index }}">
                    <ion-icon name="create-outline"></ion-icon>
                </button>
                
                <button type="button" class="btn btn-link p-1 text-danger js-delete" data-index="{{ index }}" aria-label="{{ lmsg('common.delete') }}">
                    <ion-icon name="trash-outline" aria-hidden="true"></ion-icon>
                </button>
            </div>
        </div>
    {% endverbatim %}
</script>

<script>
require(['jquery', 'domReady', 'twig_renderer'], function ($, domReady, twig) {
    // Our frontend twig template uses lmsg, so we need to expose a lmsg method for it to use
    twig.extendFunction("lmsg", function(value) {
        return lmsg(value);
    });

    domReady(function() {
        const PromptManager = {
            savedData: {{ prompts|json_encode|raw }} || [],
            workingData: [],
            maxInstructions: {{ maxInstructions }},
            editIndex: null,
            module: '{{ module }}',

            init: function() {
                this.$modal = $('#modal-' + this.module);
                this.$list = this.$modal.find('.js-prompt-list');
                this.$wrapper = this.$modal.find('.js-prompt-field-wrapper');
                this.$input = this.$modal.find('.js-prompt-input');
                this.$addBtn = this.$modal.find('.js-add-prompt');
                this.$finalSaveBtn = this.$modal.find('.js-final-save');
                this.$spinner = this.$modal.find('.js-save-spinner');
                this.$externalBadge = $('[data-target="#modal-' + this.module + '"]').find('.js-instruction-badge');

                this.workingData = [...this.savedData];

                this.bindEvents();
                this.render();
            },

            bindEvents: function() {
                this.$addBtn.on('click', () => this.toggleUI(true));
                this.$modal.on('click', '.js-cancel-prompt', () => this.toggleUI(false));
                this.$modal.on('click', '.js-save-prompt', () => this.savePrompt());
                
                this.$modal.on('hidden.bs.modal', () => this.resetToSaved());
                
                this.$modal.on('click', '.js-suggestion', (e) => this.handleSuggestion(e));
                this.$list.on('click', '.js-edit', (e) => this.handleEdit(e));
                this.$list.on('click', '.js-delete', (e) => this.handleDelete(e));

                this.$finalSaveBtn.on('click', () => this.save());
            },

            render: function() {
                var templateSource = $('#list-item-template').text();
                var template = twig.twig({ data: templateSource, autoescape: true });

                const items = this.workingData.map(function(text, i) {
                    return template.render({
                        text,
                        index: i
                    });
                }, this).join('');

                this.$list.html(items.length > 0 ? items : '<p class="text-muted small pt-2 mb-0">' + lmsg('admin.admin.ai.prompt_engineering.empty') + '</p>');

                const count = this.workingData.length;
                this.$modal.find('.js-instruction-count').text(count);

                if (count >= this.maxInstructions) {
                    this.$addBtn.prop('disabled', true);
                    this.$modal.find('.js-suggestion').prop('disabled', true);
                } else {
                    this.$addBtn.prop('disabled', false);
                    this.$modal.find('.js-suggestion').prop('disabled', false);
                }

                if (count > 0) {
                    this.$externalBadge.text(count).removeClass('d-none');
                } else {
                    this.$externalBadge.addClass('d-none');
                }
            },

            resetToSaved: function() {
                this.workingData = [...this.savedData];
                this.toggleUI(false);
                this.render();
            },

            toggleUI: function(show) {
                if (show) {
                    this.$wrapper.removeClass('d-none');
                    this.$addBtn.addClass('d-none');
                    this.$input.focus();
                } else {
                    this.$wrapper.addClass('d-none');
                    this.$addBtn.removeClass('d-none');
                    this.$input.val('').removeClass('is-invalid');
                    this.editIndex = null;
                }
            },

            handleSuggestion: function(e) {
                const text = $(e.currentTarget).data('prompt');
                this.toggleUI(true);
                this.$input.val(text).focus();
            },

            savePrompt: function() {
                const inputEl = this.$input[0];
                if (!inputEl.checkValidity()) {
                    this.$input.addClass('is-invalid');
                    return;
                }

                const val = this.$input.val().trim();

                if (!val) {
                    this.$input.addClass('is-invalid');
                    return;
                }

                if (this.editIndex !== null) {
                    this.workingData[this.editIndex] = val;
                } else {
                    this.workingData.push(val);
                }

                this.render();
                this.toggleUI(false);
            },

            handleEdit: function(e) {
                this.editIndex = $(e.currentTarget).data('index');
                this.$input.val(this.workingData[this.editIndex]);
                this.toggleUI(true);
            },

            handleDelete: function(e) {
                const index = $(e.currentTarget).data('index');
                this.workingData.splice(index, 1);
                this.render();
            },

            save: function() {
                this.$finalSaveBtn.prop('disabled', true);
                this.$spinner.removeClass('d-none');

                $.ajax({
                    url: '/admin/system/ai/update-prompt', 
                    method: 'POST',
                    data: {
                        prompts: this.workingData,
                        module: this.module
                    },
                    success: () => {
                        this.savedData = [...this.workingData];
                        this.$modal.modal('hide');
                        cla.showMessage(lmsg('admin.admin.ai.prompt_engineering.changes_saved'));
                    },
                    error: (data) => {
                        cla.showMessage(data.responseText, '', true);
                    },
                    complete: () => {
                        this.$finalSaveBtn.prop('disabled', false);
                        this.$spinner.addClass('d-none');
                    }
                });
            }
        };

        PromptManager.init();
    });
});
</script>