(function ($) {
    'use strict';

    const SifencySectionBuilder = {
        modal: null,
        closeBtn: null,
        titleInput: null,
        saveBtn: null,
        editBtn: null,

        init() {
            this.modal = $('#sifency-new-section-modal');
            if (!this.modal.length) {
                return;
            }

            if (!this.modal.hasClass('is-visible')) {
                this.modal.css('display', 'none');
            }

            this.closeBtn = this.modal.find('.sifency-modal-close');
            this.titleInput = this.modal.find('#sifency-section-title');
            this.saveBtn = this.modal.find('#sifency-save-section-draft');
            this.editBtn = this.modal.find('#sifency-create-section-elementor');

            this.bindEvents();
        },

        bindEvents() {
            $(document).on('click', '.sifency-open-new-section-modal', (e) => this.openModal(e));
            this.closeBtn.on('click', () => this.closeModal());
            this.modal.on('click', (e) => this.closeOnOverlay(e));
            this.saveBtn.on('click', (e) => this.createTemplate(e, 'draft'));
            this.editBtn.on('click', (e) => this.createTemplate(e, 'edit'));
            $(document).on('click', '.sifency-copy-btn', (e) => this.copyShortcode(e));
        },

        openModal(e) {
            e.preventDefault();
            this.modal.css('display', 'flex');
            requestAnimationFrame(() => {
                this.modal.addClass('is-visible');
            });
            setTimeout(() => this.titleInput.trigger('focus'), 150);
        },

        closeModal() {
            this.modal.removeClass('is-visible');
            setTimeout(() => {
                if (!this.modal.hasClass('is-visible')) {
                    this.modal.css('display', 'none');
                }
                this.titleInput.val('');
                this.enableButtons();
            }, 350);
        },

        closeOnOverlay(e) {
            if ($(e.target).is(this.modal)) {
                this.closeModal();
            }
        },

        disableButtons(button) {
            this.saveBtn.prop('disabled', true);
            this.editBtn.prop('disabled', true);
            if (button) {
                button.find('.spinner').addClass('is-active');
            }
        },

        enableButtons() {
            this.saveBtn.prop('disabled', false);
            this.editBtn.prop('disabled', false);
            this.modal.find('.spinner').removeClass('is-active');
        },

        createTemplate(e, action) {
            e.preventDefault();

            const title = this.titleInput.val().trim();
            if (!title) {
                alert('Please enter a section name.');
                this.titleInput.trigger('focus');
                return;
            }

            const $button = $(e.currentTarget);
            this.disableButtons($button);

            $.ajax({
                url: sifencySectionBuilder.ajaxUrl,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'sifency_create_section_template',
                    nonce: sifencySectionBuilder.nonce,
                    title,
                    redirect_action: action,
                },
                success: (res) => {
                    if (res.success) {
                        if (res.data.redirect_url) {
                            window.location.href = res.data.redirect_url;
                            return;
                        }

                        if (res.data.new_row_html) {
                            this.closeModal();

                            const $tableBody = $('table.sifency-templates-table tbody');
                            $tableBody.find('tr.no-items').remove();
                            $(res.data.new_row_html)
                                .prependTo($tableBody)
                                .hide()
                                .fadeIn(500);
                        } else {
                            alert('Draft saved, but an issue occurred updating the list. Reloading...');
                            window.location.reload();
                        }
                    } else {
                        alert('Error: ' + (res.data.message || 'An unknown error occurred.'));
                        this.enableButtons();
                    }
                },
                error: (jqXHR, textStatus) => {
                    alert('An AJAX error occurred: ' + textStatus + '. Please check the console and try again.');
                    console.error('Sifency AJAX Error:', textStatus, jqXHR.responseText);
                    this.enableButtons();
                },
            });
        },

        copyShortcode(e) {
            e.preventDefault();
            const $btn = $(e.currentTarget);
            const shortcode = $btn.siblings('.sifency-shortcode-input').val();

            if (!shortcode) {
                return;
            }

            if (navigator.clipboard) {
                navigator.clipboard.writeText(shortcode).then(() => {
                    this.showCopySuccess($btn);
                });
            } else {
                $btn.siblings('.sifency-shortcode-input').select();
                document.execCommand('copy');
                this.showCopySuccess($btn);
            }
        },

        showCopySuccess($btn) {
            const $icon = $btn.find('.dashicons');
            const originalColor = $btn.css('color');
            $icon.removeClass('dashicons-admin-page').addClass('dashicons-yes-alt');
            $btn.css('color', '#46b450');

            setTimeout(() => {
                $icon.removeClass('dashicons-yes-alt').addClass('dashicons-admin-page');
                $btn.css('color', originalColor);
            }, 2000);
        },
    };

    $(function () {
        SifencySectionBuilder.init();
    });
})(jQuery);
