(function ($) {
    'use strict';

    const TemplateMetaEditor = {
        config: null,
        tooltipTransitionMs: 220,

        init(config) {
            this.config = config || window.sifencyTemplateInlineEdit;
            if (!this.config || !this.config.ajaxUrl) {
                return;
            }
            this.bindEvents();
        },

        bindEvents() {
            const self = this;

            $(document).on('click', '.sifency-edit-template-meta', function (e) {
                e.preventDefault();
                e.stopPropagation();
                const $wrap = $(this).closest('.sifency-template-inline-edit');
                const $tooltip = $wrap.find('.sifency-template-meta-tooltip');

                if ($tooltip.hasClass('is-open')) {
                    self.closeEdit($wrap, true);
                } else {
                    self.openEdit($wrap);
                }
            });

            $(document).on('click', '.sifency-tooltip-close', function (e) {
                e.preventDefault();
                self.closeEdit($(this).closest('.sifency-template-inline-edit'), true);
            });

            $(document).on('click', '.sifency-save-template-meta', function (e) {
                e.preventDefault();
                e.stopPropagation();
                self.save($(this).closest('.sifency-template-inline-edit'));
            });

            $(document).on('click', '.sifency-template-meta-tooltip-card', function (e) {
                e.stopPropagation();
            });

            $(document).on('click', function (e) {
                if ($(e.target).closest('.sifency-template-meta-tooltip, .sifency-edit-template-meta').length) {
                    return;
                }
                self.closeAll();
            });

            $(document).on('keydown', '.sifency-template-title-input, .sifency-template-slug-input, .sifency-template-status-input', function (e) {
                const $wrap = $(this).closest('.sifency-template-inline-edit');
                if (e.key === 'Enter' && !$(this).is('select')) {
                    e.preventDefault();
                    self.save($wrap);
                }
                if (e.key === 'Escape') {
                    e.preventDefault();
                    self.closeEdit($wrap, true);
                }
            });
        },

        closeAll(except$wrap) {
            const self = this;
            $('.sifency-template-meta-tooltip.is-open').each(function () {
                const $owner = $(this).closest('.sifency-template-inline-edit');
                if (except$wrap && except$wrap.is($owner)) {
                    return;
                }
                self.closeEdit($owner, true);
            });
        },

        openEdit($wrap) {
            const $tooltip = $wrap.find('.sifency-template-meta-tooltip');
            const $titleInput = $wrap.find('.sifency-template-title-input');
            const $slugInput = $wrap.find('.sifency-template-slug-input');
            const $statusInput = $wrap.find('.sifency-template-status-input');

            this.closeAll($wrap);

            $wrap.data('original-title', $titleInput.val());
            $wrap.data('original-slug', $slugInput.val());
            $wrap.data('original-status', $statusInput.val());

            $tooltip.removeAttr('hidden');
            requestAnimationFrame(() => {
                $tooltip.addClass('is-open');
                $titleInput.trigger('focus');
            });
        },

        closeEdit($wrap, restoreValues) {
            const $tooltip = $wrap.find('.sifency-template-meta-tooltip');
            const $titleInput = $wrap.find('.sifency-template-title-input');
            const $slugInput = $wrap.find('.sifency-template-slug-input');
            const $statusInput = $wrap.find('.sifency-template-status-input');
            const $feedback = $wrap.find('.sifency-inline-save-feedback');

            if (restoreValues) {
                $titleInput.val($wrap.data('original-title') || '');
                $slugInput.val($wrap.data('original-slug') || '');
                $statusInput.val($wrap.data('original-status') || '');
            }

            $feedback.removeClass('is-error is-success').text('');
            $tooltip.removeClass('is-open');

            setTimeout(() => {
                if (!$tooltip.hasClass('is-open')) {
                    $tooltip.attr('hidden', true);
                }
            }, this.tooltipTransitionMs);
        },

        updateView($wrap, title, slug, status, statusLabel) {
            $wrap.find('.sifency-template-title-display').text(title);
            $wrap.attr('data-slug', slug);
            $wrap.attr('data-status', status);

            const labels = (this.config && this.config.statusLabels) || {};
            const label = statusLabel || labels[status] || status;

            const $row = $wrap.closest('tr');
            const $statusDisplay = $row.find('.sifency-template-status-display');

            if ($statusDisplay.length) {
                $statusDisplay
                    .text(label)
                    .attr('data-status', status);

                const draftNote = (this.config && this.config.draftTooltip) || '';
                if (status === 'draft' || status === 'pending') {
                    $statusDisplay.attr('data-tooltip', draftNote);
                } else {
                    $statusDisplay.removeAttr('data-tooltip');
                }
            }

            const $card = $wrap.closest('.sifency-card-for-cpt');
            if ($card.length) {
                const $badge = $card.find('.card-meta .status-badge');
                if ($badge.length) {
                    $badge
                        .removeClass('badge-publish badge-draft badge-pending badge-private badge-trash')
                        .addClass('badge-' + status)
                        .text(label);
                }

                const $statusBar = $card.find('.card-status');
                if ($statusBar.length) {
                    $statusBar
                        .removeClass('status-publish status-draft status-pending status-private status-trash')
                        .addClass('status-' + status);
                }
            }
        },

        save($wrap) {
            const self = this;
            const templateId = $wrap.data('template-id');
            const $titleInput = $wrap.find('.sifency-template-title-input');
            const $slugInput = $wrap.find('.sifency-template-slug-input');
            const $statusInput = $wrap.find('.sifency-template-status-input');
            const $feedback = $wrap.find('.sifency-inline-save-feedback');
            const $saveBtn = $wrap.find('.sifency-save-template-meta');

            const title = $titleInput.val().trim();
            const slug = $slugInput.val().trim();
            const status = $statusInput.val();

            if (!title) {
                alert((this.config && this.config.i18n && this.config.i18n.emptyTitle) || 'Please enter a title.');
                $titleInput.trigger('focus');
                return;
            }

            $saveBtn.prop('disabled', true);
            $feedback.removeClass('is-error is-success').text(
                (this.config && this.config.i18n && this.config.i18n.saving) || 'Saving...'
            );

            $.ajax({
                url: this.config.ajaxUrl,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: this.config.action,
                    nonce: this.config.nonce,
                    template_id: templateId,
                    title,
                    slug,
                    post_status: status,
                },
            }).done((res) => {
                if (res.success) {
                    const savedTitle = res.data.title || title;
                    const savedSlug = res.data.slug || slug;
                    const savedStatus = res.data.status || status;
                    const savedStatusLabel = res.data.status_label || '';

                    $titleInput.val(savedTitle);
                    $slugInput.val(savedSlug);
                    $statusInput.val(savedStatus);
                    self.updateView($wrap, savedTitle, savedSlug, savedStatus, savedStatusLabel);
                    self.closeEdit($wrap, false);
                } else {
                    $feedback
                        .removeClass('is-success')
                        .addClass('is-error')
                        .text((res.data && res.data.message) || 'Update failed');
                }
            }).fail(() => {
                $feedback.removeClass('is-success').addClass('is-error').text('Request failed');
            }).always(() => {
                $saveBtn.prop('disabled', false);
            });
        },
    };

    $(function () {
        TemplateMetaEditor.init();
    });

    window.SifencyTemplateMetaEditor = TemplateMetaEditor;
})(jQuery);
