/* t9p-tmv-script.js | Copyright (C) 2026 The 9 Dollar Plugins | GPLv2 or later */

(function ($) {
    'use strict';

    // ── Helpers ───────────────────────────────────────────────────────────

    function t9p_tmv_showStatus(msg, error) {
        var $el = $('#t9p-tmv-status-msg');
        $el.removeClass('t9p-tmv-error').text(msg);
        if (error) {
            $el.addClass('t9p-tmv-error');
        }
        clearTimeout($el.data('t9p_tmv_timer'));
        $el.css('opacity', 1);
        $el.data('t9p_tmv_timer', setTimeout(function () {
            $el.css('opacity', 0);
        }, 3000));
    }

    function t9p_tmv_ajax(data, onSuccess) {
        $.post(t9pTmvValet.ajax_url, data, function (res) {
            if (res && res.success) {
                onSuccess(res);
            } else {
                t9p_tmv_showStatus((res && res.data && res.data.message) ? res.data.message : t9pTmvValet.text_error, true);
            }
        }, 'json').fail(function () {
            t9p_tmv_showStatus(t9pTmvValet.text_error, true);
        });
    }

    function t9p_tmv_showApplyButton() {
        var $btn = $('#t9p-tmv-apply-btn');
        $btn.show();
        setTimeout(function () {
            $btn.addClass('t9p-tmv-pulse');
        }, 20);
        setTimeout(function () {
            $btn.removeClass('t9p-tmv-pulse');
        }, 3020);
    }

    // ── Hide / show checkboxes ────────────────────────────────────────────

    function t9p_tmv_setupHideCheckboxes() {
        $('#t9p-tmv-menu-table').on('change', '.t9p-tmv-hide-cb', function () {
            var $cb = $(this);
            var slug = $cb.data('slug');
            var hide = $cb.is(':checked') ? '1' : '0';
            var $row = $cb.closest('tr');
            var isParent = $cb.hasClass('t9p-tmv-parent-cb') ? '1' : '0';

            t9p_tmv_showStatus(t9pTmvValet.text_saving);
            t9p_tmv_ajax({
                action: 't9p_tmv_toggle_item',
                _ajax_nonce: t9pTmvValet.nonce,
                slug: slug,
                hidden: hide,
                is_parent: isParent
            }, function () {
                if (hide === '1') {
                    if (isParent === '1') {
                        $row.addClass('t9p-tmv-row-hidden');
                        $row.find('.t9p-tmv-sub-cb').prop('checked', true).prop('disabled', true);
                    }
                } else {
                    if (isParent === '1') {
                        $row.removeClass('t9p-tmv-row-hidden');
                        $row.find('.t9p-tmv-sub-cb').prop('checked', false).prop('disabled', false);
                    }
                }
                t9p_tmv_showStatus(t9pTmvValet.text_saved);
                t9p_tmv_showApplyButton();
            });
        });
    }

    // ── Drag-and-drop reordering ──────────────────────────────────────────

    function t9p_tmv_setupSortable() {
        var $tbody = $('#t9p-tmv-sortable');
        if (!$tbody.length) {
            return;
        }

        $tbody.sortable({
            handle: '.t9p-tmv-drag-handle',
            axis: 'y',
            cursor: 'grabbing',
            placeholder: 't9p-tmv-sortable-placeholder',
            forcePlaceholderSize: true,

            createPlaceholder: function (_ui, item) {
                var cols = item.children().length;
                var $ph = $('<tr class="t9p-tmv-sortable-placeholder">');
                for (var i = 0; i < cols; i++) {
                    $ph.append('<td>&nbsp;</td>');
                }
                return $ph;
            },

            stop: function () {
                var order = [];
                $tbody.find('tr[data-slug]').each(function () {
                    order.push($(this).data('slug'));
                });

                t9p_tmv_showStatus(t9pTmvValet.text_saving);
                t9p_tmv_ajax({
                    action: 't9p_tmv_save_order',
                    _ajax_nonce: t9pTmvValet.nonce,
                    order: order
                }, function () {
                    t9p_tmv_showStatus(t9pTmvValet.text_saved);
                    t9p_tmv_showApplyButton();
                });
            }
        });

        $tbody.disableSelection();
    }

    // ── Apply Changes button ──────────────────────────────────────────────

    function t9p_tmv_setupApplyButton() {
        $('#t9p-tmv-apply-btn').on('click', function () {
            window.location.reload();
        });
    }

    // ── Feature dropdowns ─────────────────────────────────────────────────

    function t9p_tmv_setupFeatureDropdowns() {
        
        $('#t9p-tmv-delete-select').on('change', function () {
            t9p_tmv_showStatus(t9pTmvValet.text_saving);
            t9p_tmv_ajax({
                action: 't9p_tmv_save_delete_setting',
                _ajax_nonce: t9pTmvValet.nonce,
                delete_on_uninstall: $(this).val()
            }, function () {
                t9p_tmv_showStatus(t9pTmvValet.text_saved);
            });
        });
    }

    // ── Init ──────────────────────────────────────────────────────────────

    $(function () {
        t9p_tmv_setupHideCheckboxes();
        t9p_tmv_setupSortable();
        t9p_tmv_setupApplyButton();
        t9p_tmv_setupFeatureDropdowns();
        
    });

}(jQuery));
