/**
 * AIEO Competitions — admin JS. Powers (a) the desktop/mobile image media
 * pickers on both the Competitions admin page and the CPT editor meta box,
 * (b) the "Create competition" AJAX form on the admin page, and (c) the
 * copy-to-clipboard share-link buttons. Defensive: each handler is delegated
 * and no-ops when its elements aren't on the page.
 */
(function ($) {
    'use strict';

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

    // --- Media pickers (module create form + CPT meta box) ---
    $(document).on('click', '.aieo-comp-image-select', function (e) {
        e.preventDefault();
        if (typeof wp === 'undefined' || !wp.media) { return; }
        var $field = $(this).closest('.aieo-comp-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-comp-image-id').val(att.id);
            $field.find('.aieo-comp-image-preview').attr('src', url).show();
            $field.find('.aieo-comp-image-remove').show();
        });
        frame.open();
    });

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

    // --- Copy share link ---
    $(document).on('click', '.aieo-comp-copy', function (e) {
        e.preventDefault();
        var url = $(this).data('url') || '';
        var btn = this;
        var orig = $(btn).text();
        var done = function () { $(btn).text(i18n.copied || 'Copied!'); setTimeout(function () { $(btn).text(orig); }, 1200); };
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(url).then(done, function () { window.prompt('Copy:', url); });
        } else {
            window.prompt('Copy:', url);
        }
    });

    // --- Winner selection (CPT editor meta box) ---
    function escHtml(s) { return $('<div>').text(s == null ? '' : String(s)).html(); }

    function renderWinners(winners) {
        var $ul = $('#aieo-comp-winners-list');
        $ul.empty();
        (winners || []).forEach(function (w) {
            $ul.append(
                '<li data-pid="' + parseInt(w.pid, 10) + '" style="margin:0 0 6px;padding:6px 8px;background:#f6f7f7;border-radius:4px;">' +
                '<strong>' + escHtml(w.name || '—') + '</strong> ' +
                '<span style="color:#646970;">' + escHtml(w.email) + '</span> ' +
                '<button type="button" class="button-link aieo-comp-winner-remove" title="' + (i18n.removeWinner || 'Remove winner') + '" style="color:#b32d2e;float:right;">×</button>' +
                '</li>'
            );
        });
    }

    $(document).on('click', '#aieo-comp-draw-winners', function (e) {
        e.preventDefault();
        var $box = $('#aieo-comp-winners-box');
        var cid = parseInt($box.data('comp'), 10) || 0;
        var target = parseInt($box.data('target'), 10) || 1;
        var $st = $('#aieo-comp-winners-status'), btn = this;
        $(btn).prop('disabled', true);
        $st.css('color', '#646970').text(i18n.saving || 'Saving…');
        $.post(cfg.ajaxurl, {
            action: 'aieo_competition_draw_winners',
            nonce: cfg.nonce,
            competition_id: cid,
            count: target
        }).done(function (resp) {
            $(btn).prop('disabled', false); $st.text('');
            if (resp && resp.success) { renderWinners(resp.data.winners); }
            else { $st.css('color', '#b32d2e').text((resp && resp.data && resp.data.message) || 'Error'); }
        }).fail(function () { $(btn).prop('disabled', false); $st.css('color', '#b32d2e').text('Request failed'); });
    });

    $(document).on('click', '.aieo-comp-winner-remove', function (e) {
        e.preventDefault();
        var $li = $(this).closest('li'), pid = parseInt($li.data('pid'), 10) || 0;
        $.post(cfg.ajaxurl, {
            action: 'aieo_competition_toggle_winner',
            nonce: cfg.nonce,
            participant_id: pid,
            on: 0
        }).done(function () { $li.remove(); });
    });

    // --- Save global page messages (all competitions) ---
    $(document).on('click', '#aieo-comp-settings-save', function (e) {
        e.preventDefault();
        var btn = this, $status = $('#aieo-comp-settings-status');
        $(btn).prop('disabled', true);
        $status.css('color', '#646970').text(i18n.saving || 'Saving…');
        $.post(cfg.ajaxurl, {
            action:    'aieo_competitions_settings_save',
            nonce:     cfg.nonce,
            msg_soon:     $('#aieo-comp-msg-soon').val() || '',
            msg_ended:    $('#aieo-comp-msg-ended').val() || '',
            msg_announce: $('#aieo-comp-msg-announce').val() || '',
            color_live:   $('#aieo-comp-color-live').val() || '',
            color_ended:  $('#aieo-comp-color-ended').val() || '',
            color_before: $('#aieo-comp-color-before').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 competition (admin page only) ---
    $(document).on('click', '#aieo-comp-create-btn', function (e) {
        e.preventDefault();
        var name = ($('#aieo-comp-name').val() || '').trim();
        var $status = $('#aieo-comp-create-status');
        if (!name) { $status.css('color', '#b32d2e').text(i18n.noname || 'Please enter a competition name.'); return; }

        var imgD = 0, imgM = 0;
        $('#aieo-comp-create .aieo-comp-image-field').each(function () {
            var which = $(this).data('which');
            var id = parseInt($(this).find('.aieo-comp-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_competitions_save',
            nonce:       cfg.nonce,
            post_id:     parseInt($('#aieo-comp-post-id').val(), 10) || 0,
            name:        name,
            gf_id:       parseInt($('#aieo-comp-gf').val(), 10) || 0,
            short_desc:  $('#aieo-comp-desc').val() || '',
            img_desktop: imgD,
            img_mobile:  imgM,
            start:       $('#aieo-comp-start').val() || '',
            end:         $('#aieo-comp-end').val() || '',
            announce:    $('#aieo-comp-announce').val() || '',
            // Associations (reuse the discount-targeting pickers) + prize config.
            brands:        $('#aieo-comp-brands').val() || [],
            categories:    $('#aieo-comp-categories').val() || [],
            comp_products: $('#aieo-comp-create select[name="comp_products[]"]').val() || [],
            winners_count: parseInt($('#aieo-comp-winners').val(), 10) || 0,
            prize_value:   parseFloat($('#aieo-comp-prize').val()) || 0
        }).done(function (resp) {
            if (resp && resp.success) {
                $status.css('color', '#1a7f37').text(i18n.saved || 'Saved.');
                window.location.reload(); // re-render with the new competition 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');
        });
    });

    // --- Insights: precomputed off the request path. The button recomputes on
    //     demand; an empty panel (never built yet) auto-triggers one build so
    //     the first visit doesn't block ~10s rendering it inline. Either way we
    //     reload once the cache is written, so the PHP stays the single source
    //     of truth for the markup. ---
    function refreshStats($btn, auto) {
        var $asof = $('#aieo-comp-stats-asof');
        if ($btn && $btn.length) { $btn.prop('disabled', true); }
        $asof.text(i18n.refreshing || 'Refreshing…');
        $.post(cfg.ajaxurl, {
            action: 'aieo_competitions_refresh_stats',
            nonce: cfg.nonce
        }).done(function (resp) {
            if (resp && resp.success) {
                window.location.reload(); // re-render Insights from the fresh cache
            } else {
                if ($btn && $btn.length) { $btn.prop('disabled', false); }
                $asof.css('color', '#b32d2e').text((resp && resp.data && resp.data.message) || 'Error');
            }
        }).fail(function () {
            if ($btn && $btn.length) { $btn.prop('disabled', false); }
            // On the auto-build path don't nag with an error — a scheduled run
            // will fill the cache; the operator can also click Refresh.
            if (!auto) { $asof.css('color', '#b32d2e').text('Request failed'); }
        });
    }

    $(document).on('click', '#aieo-comp-refresh-stats', function (e) {
        e.preventDefault();
        refreshStats($(this), false);
    });

    // Auto-refresh cadence (off / hourly / daily / weekly / monthly) — saves on
    // change; the server reschedules (or clears) the cron immediately.
    $(document).on('change', '#aieo-comp-stats-cadence', function () {
        var val = $(this).val(), $asof = $('#aieo-comp-stats-asof');
        $asof.css('color', '#646970').text(i18n.saving || 'Saving…');
        $.post(cfg.ajaxurl, {
            action: 'aieo_competitions_stats_cadence',
            nonce: cfg.nonce,
            cadence: val
        }).done(function (resp) {
            $asof.text((resp && resp.success) ? (i18n.saved || 'Saved.') : ((resp && resp.data && resp.data.message) || 'Error'));
        }).fail(function () {
            $asof.css('color', '#b32d2e').text('Request failed');
        });
    });

    $(function () {
        if ($('#aieo-comp-insights[data-stats="empty"]').length) {
            refreshStats($('#aieo-comp-refresh-stats'), true);
        }
    });

})(jQuery);
