/* Storzen  v3.0  —  Admin JS */
(function ($) {
    'use strict';

    /* ── Global toast ── */
    window.pkToast = function (msg, type) {
        var $t = $('#pkToast');
        if (!$t.length) return;
        $t.removeClass('sz-toast--show sz-toast--error').find('.sz-toast__msg').text(msg);
        if (type === 'error') $t.addClass('sz-toast--error');
        void $t[0].offsetWidth;
        $t.addClass('sz-toast--show');
        clearTimeout(window._pkToastTimer);
        window._pkToastTimer = setTimeout(function () { $t.removeClass('sz-toast--show'); }, 2800);
    };

    /* ── Collect all pk_fields[] from a container ── */
    function collectFields($ctx) {
        var out = {};
        $ctx.find('[name^="pk_fields["]').each(function () {
            var $el = $(this);
            var m   = $el.attr('name').match(/pk_fields\[(.+?)\]/);
            if (!m) return;
            var key = m[1];

            if ($el.is(':checkbox')) {
                // checkbox groups use []
                var isGroup = $el.attr('name').endsWith('[]');
                if (isGroup) {
                    if (!out[key]) out[key] = [];
                    if ($el.is(':checked')) out[key].push($el.val());
                } else {
                    out[key] = $el.is(':checked') ? '1' : '0';
                }
            } else if ($el.is(':radio')) {
                if ($el.is(':checked')) out[key] = $el.val();
            } else {
                out[key] = $el.val();
            }
        });
        return out;
    }

    /* ── Save button ── */
    $(document).on('click', '.js-sz-save', function () {
        var $btn = $(this);
        if ($btn.hasClass('sz-btn--loading')) return;

        var menu    = $btn.data('menu');
        var tab     = $btn.data('tab');
        var $content = $('#pkContent');
        var fields  = collectFields($content);

        $btn.addClass('sz-btn--loading').text(PK.i18n.saving);

        $.post(PK.ajax_url, {
            action:    'pk_save',
            nonce:     PK.nonce,
            menu:      menu,
            tab:       tab,
            pk_fields: fields,
        })
        .done(function (r) {
            pkToast(r.success ? PK.i18n.saved : (r.data && r.data.message) || PK.i18n.error,
                    r.success ? 'success' : 'error');
        })
        .fail(function () { pkToast(PK.i18n.error, 'error'); })
        .always(function () { $btn.removeClass('sz-btn--loading').text(PK.i18n.save); });
    });

    /* ── Ctrl/Cmd+S shortcut ── */
    $(document).on('keydown', function (e) {
        if ((e.ctrlKey || e.metaKey) && e.key === 's') {
            e.preventDefault();
            $('.js-sz-save:first').trigger('click');
        }
    });

    /* ── WP Media uploader for Image fields ── */
    $(document).on('click', '.js-sz-media-select', function (e) {
        e.preventDefault();
        var target   = $(this).data('target');
        var preview  = $(this).data('preview');
        var $btn     = $(this);

        if (typeof wp === 'undefined' || !wp.media) return;

        var frame = wp.media({ title: 'Select Image', button: { text: 'Use Image' }, multiple: false });
        frame.on('select', function () {
            var att = frame.state().get('selection').first().toJSON();
            $('#' + target).val(att.id);
            var $preview = $('#' + preview);
            $preview.show().html('<img src="' + att.sizes?.thumbnail?.url || att.url + '" alt="">');
            $btn.text('Change Image');
        });
        frame.open();
    });

    $(document).on('click', '.js-sz-media-remove', function (e) {
        e.preventDefault();
        var target  = $(this).data('target');
        var preview = $(this).data('preview');
        $('#' + target).val('');
        $('#' + preview).hide().empty();
        $(this).closest('.sz-image-actions').find('.js-sz-media-select').text('Select Image');
    });

}(jQuery));
