/**
 * AIEO Events — admin JS. Powers (a) the desktop/mobile image media pickers on
 * both the Events admin page and the CPT editor meta box, (b) the global
 * "Page messages" save, and (c) the "Create event" AJAX quick-create form.
 * Mirrors aieo-competitions-admin.js. Defensive: every handler is delegated and
 * no-ops when its elements aren't on the page.
 */
(function ($) {
    'use strict';

    var cfg  = window.aieoEvents || {};
    var i18n = cfg.i18n || {};

    // --- Media pickers (module create form + CPT meta box) ---
    $(document).on('click', '.aieo-event-image-select', function (e) {
        e.preventDefault();
        if (typeof wp === 'undefined' || !wp.media) { return; }
        var $field = $(this).closest('.aieo-event-image-field');
        var frame = wp.media({
            title: i18n.select || 'Select image',
            button: { text: i18n.use || 'Use this image' },
            library: { type: 'image' },
            multiple: false
        });
        frame.on('select', function () {
            var att = frame.state().get('selection').first().toJSON();
            var url = (att.sizes && att.sizes.medium) ? att.sizes.medium.url : att.url;
            $field.find('.aieo-event-image-id').val(att.id);
            $field.find('.aieo-event-image-preview').attr('src', url).show();
            $field.find('.aieo-event-image-remove').show();
        });
        frame.open();
    });

    $(document).on('click', '.aieo-event-image-remove', function (e) {
        e.preventDefault();
        var $field = $(this).closest('.aieo-event-image-field');
        $field.find('.aieo-event-image-id').val(0);
        $field.find('.aieo-event-image-preview').attr('src', '').hide();
        $(this).hide();
    });

    // --- Rich invitation body: read live TinyMCE content (fallback to textarea) ---
    function inviteBody() {
        var ed = (window.tinyMCE && tinyMCE.get('aieoeventinvitebody'));
        if (ed && !ed.isHidden()) { return ed.getContent(); }
        return $('#aieoeventinvitebody').val() || '';
    }

    // --- Save global page messages (all events) ---
    $(document).on('click', '#aieo-event-settings-save', function (e) {
        e.preventDefault();
        var btn = this, $status = $('#aieo-event-settings-status');
        $(btn).prop('disabled', true);
        $status.css('color', '#646970').text(i18n.saving || 'Saving…');
        $.post(cfg.ajaxurl, {
            action:    'aieo_events_settings_save',
            nonce:     cfg.nonce,
            msg_soon:  $('#aieo-event-msg-soon').val() || '',
            msg_ended: $('#aieo-event-msg-ended').val() || ''
        }).done(function (resp) {
            $(btn).prop('disabled', false);
            if (resp && resp.success) {
                $status.css('color', '#1a7f37').text(i18n.saved || 'Saved.');
            } else {
                $status.css('color', '#b32d2e').text((resp && resp.data && resp.data.message) || 'Error');
            }
        }).fail(function () {
            $(btn).prop('disabled', false);
            $status.css('color', '#b32d2e').text('Request failed');
        });
    });

    // --- Create event (admin page only) ---
    $(document).on('click', '#aieo-event-create-btn', function (e) {
        e.preventDefault();
        var name = ($('#aieo-event-name').val() || '').trim();
        var $status = $('#aieo-event-create-status');
        if (!name) { $status.css('color', '#b32d2e').text(i18n.noname || 'Please enter an event name.'); return; }

        var imgD = 0, imgM = 0;
        $('#aieo-event-create .aieo-event-image-field').each(function () {
            var which = $(this).data('which');
            var id = parseInt($(this).find('.aieo-event-image-id').val(), 10) || 0;
            if (which === 'desktop') { imgD = id; } else if (which === 'mobile') { imgM = id; }
        });

        var btn = this;
        $(btn).prop('disabled', true);
        $status.css('color', '#646970').text(i18n.saving || 'Saving…');

        $.post(cfg.ajaxurl, {
            action:         'aieo_events_save',
            nonce:          cfg.nonce,
            post_id:        parseInt($('#aieo-event-post-id').val(), 10) || 0,
            name:           name,
            location:       $('#aieo-event-location').val() || '',
            map_url:        $('#aieo-event-map-url').val() || '',
            short_desc:     $('#aieo-event-desc').val() || '',
            img_desktop:    imgD,
            img_mobile:     imgM,
            start:          $('#aieo-event-start').val() || '',
            end:            $('#aieo-event-end').val() || '',
            rsvp_deadline:  $('#aieo-event-rsvp-deadline').val() || '',
            gf_id:          parseInt($('#aieo-event-gf').val(), 10) || 0,
            invite_subject: $('#aieo-event-invite-subject').val() || '',
            invite_body:    inviteBody(),
            fee:            parseFloat($('#aieo-event-fee').val()) || 0,
            currency:       $('#aieo-event-currency').val() || '',
            // Associations (reuse the discount-targeting pickers).
            brands:         $('#aieo-event-brands').val() || [],
            categories:     $('#aieo-event-categories').val() || [],
            event_products: $('#aieo-event-create select[name="event_products[]"]').val() || []
        }).done(function (resp) {
            if (resp && resp.success) {
                $status.css('color', '#1a7f37').text(i18n.saved || 'Saved.');
                window.location.reload(); // re-render with the new event in the list
            } else {
                $(btn).prop('disabled', false);
                $status.css('color', '#b32d2e').text((resp && resp.data && resp.data.message) || 'Error');
            }
        }).fail(function () {
            $(btn).prop('disabled', false);
            $status.css('color', '#b32d2e').text('Request failed');
        });
    });

})(jQuery);
