/* Eventit Events - admin page behaviour (color pickers, live preview, shortcode builder) */
jQuery(function ($) {

    var $form = $('#eventit-style-form');
    var $frame = $('#eventit-preview-frame');

    var $stage = $('#eventit-preview-stage');
    var $scaleLabel = $('#eventit-preview-scale');
    var previewWidth = parseInt($('.eventit-preview-width.is-active').data('width'), 10) || 1280;
    var previewLayout = 'list';
    var previewColumns = 0;

    /* The preview iframe renders at a real device width and is scaled down to fit
       the admin column. Scaling (rather than just making the frame narrow) is what
       keeps the media/container queries honest: at 1280 the boxed grid shows three
       columns just like on the live site, even though the admin card is narrower. */
    function eventitFitPreview() {
        var frame = $frame.get(0);
        var stage = $stage.get(0);
        if (!frame || !stage) {
            return;
        }

        var available = stage.clientWidth;
        if (!available) {
            return;
        }

        var scale = Math.min(1, available / previewWidth);
        var height = 520;
        try {
            var doc = frame.contentDocument;
            if (doc && doc.documentElement) {
                height = Math.max(120, doc.documentElement.scrollHeight);
            }
        } catch (e) {
            /* same-origin srcdoc, should not happen - keep the fallback height */
        }

        frame.style.width = previewWidth + 'px';
        frame.style.height = height + 'px';
        frame.style.transform = 'scale(' + scale + ')';
        frame.style.left = Math.max(0, (available - previewWidth * scale) / 2) + 'px';
        stage.style.height = Math.ceil(height * scale) + 'px';

        $scaleLabel.text(previewWidth + ' px' + (scale < 0.995 ? ' · ' + Math.round(scale * 100) + ' %' : ''));
    }

    $frame.on('load', function () {
        eventitFitPreview();
        /* Late-loading webfonts can change the height */
        setTimeout(eventitFitPreview, 250);
        setTimeout(eventitFitPreview, 1000);
    });
    $(window).on('resize', eventitFitPreview);
    eventitFitPreview();

    /* ------------------------------------------------------------------
       Live preview: serialize the form, let PHP generate CSS + markup.
       One source of truth - the preview is rendered by the same code as
       the frontend shortcode.
       ------------------------------------------------------------------ */
    var previewTimer = null;
    var previewRequest = null;

    function refreshPreview() {
        if (!$form.length || typeof eventitAdmin === 'undefined') {
            return;
        }
        clearTimeout(previewTimer);
        previewTimer = setTimeout(function () {
            if (previewRequest && previewRequest.readyState !== 4) {
                previewRequest.abort();
            }
            var data = $form.serialize()
                + '&action=eventit_events_preview&nonce=' + encodeURIComponent(eventitAdmin.previewNonce)
                + '&preview_layout=' + encodeURIComponent(previewLayout)
                + '&preview_columns=' + encodeURIComponent(previewColumns);
            previewRequest = $.post(eventitAdmin.ajaxUrl, data, function (response) {
                if (!response || !response.success || !response.data.doc) {
                    return;
                }
                /* Replacing srcdoc reloads the iframe, which fires 'load' -> refit */
                $frame.attr('srcdoc', response.data.doc);
            });
        }, 120);
    }

    /* Color pickers - change + clear both refresh the preview */
    $('.eventit-color-field').wpColorPicker({
        change: function () { refreshPreview(); },
        clear: function () { refreshPreview(); }
    });

    /* Everything else in the form */
    $form.on('change input', 'select, input[type="range"], textarea', refreshPreview);

    /* Range sliders: show value */
    $form.on('input change', 'input[type="range"]', function () {
        $(this).siblings('output').text(this.value);
    });

    /* Theme dependent hints + the one field that does not apply everywhere.
       Date and tag colours work on every theme now, so they are never hidden.
       The main colour is different: with the per-category palette the categories
       own the colour, so the field is hidden rather than left as a control that
       looks live but changes nothing. */
    function updateThemeState() {
        var theme = String($('#eventit-opt-color-theme').val());
        $('.eventit-theme-hint').hide().filter('[data-theme="' + theme + '"]').show();
        $('[data-option="accent-color"]').toggle(theme !== '1');
    }
    $('#eventit-opt-color-theme').on('change', updateThemeState);
    updateThemeState();

    /* Preview background + width controls (do not affect the saved settings) */
    $('#eventit-preview-dark').on('change', function () {
        $('.eventit-preview').toggleClass('eventit-preview-on-dark', this.checked);
    });

    /* One layout at a time: full width, or the boxed view at 2, 3 or 4 columns */
    $('.eventit-preview-layout').on('click', function () {
        previewLayout = $(this).data('layout') === 'boxed' ? 'boxed' : 'list';
        previewColumns = parseInt($(this).data('columns'), 10) || 0;
        $('.eventit-preview-layout').removeClass('is-active');
        $(this).addClass('is-active');
        refreshPreview();
    });

    $('.eventit-preview-width').on('click', function () {
        previewWidth = parseInt($(this).data('width'), 10) || 1280;
        $('.eventit-preview-width').removeClass('is-active');
        $(this).addClass('is-active');
        eventitFitPreview();
        /* Re-measure once the reflow at the new width has settled */
        setTimeout(eventitFitPreview, 120);
    });

    /* Reset confirmation */
    $('.eventit-reset-button').on('click', function (e) {
        if (!window.confirm('Nulstil alle udseende-indstillinger til standard?')) {
            e.preventDefault();
        }
    });

    /* ------------------------------------------------------------------
       Shortcode builder ("Lav shortcode" page)
       ------------------------------------------------------------------ */
    function eventitBuildShortcode() {
        var shortcode = '[eventit-events';
        var boxed = $('#eventit-choose-view-type').val() === '1';
        var summary = [];

        $('#eventit-builder-columns').toggle(boxed);

        var events = $('.eventit-event-checkbox:checked').map(function () {
            return this.value;
        }).get();

        var categories = $('.eventit-category-checkbox:checked').map(function () {
            return this.value;
        }).get();

        /* An explicit list of events wins over the category filter - mirror that
           here so the builder never produces a shortcode that lies about itself. */
        if (events.length > 0) {
            shortcode += ' events="' + events.join(', ') + '"';
            summary.push('Viser <b>' + events.length + '</b> valgt' + (events.length === 1 ? ' event' : 'e events'));
            if (categories.length > 0) {
                summary.push('Kategorivalget bruges ikke, når du har valgt bestemte events');
            }
        } else if (categories.length > 0) {
            shortcode += ' categories="' + categories.join(', ') + '"';
            summary.push('Viser alle events i <b>' + categories.length + '</b> valgt' + (categories.length === 1 ? ' kategori' : 'e kategorier'));
        } else {
            summary.push('Viser <b>alle</b> dine events');
        }

        if (boxed) {
            shortcode += ' boxed="1"';
            var columns = $('#eventit-choose-columns').val();
            if (columns) {
                shortcode += ' columns="' + columns + '"';
                summary.push('Box visning i ' + columns + ' kolonner');
            } else {
                summary.push('Box visning');
            }
        } else {
            summary.push('Fuld bredde');
        }

        shortcode += ']';
        $('#eventit-show-shortcode').text(shortcode);

        $('#eventit-result-summary').html(summary.map(function (line) {
            return '<li>' + line + '</li>';
        }).join(''));

        var $counter = $('#eventit-pick-counter');
        if ($counter.length) {
            $counter.text(events.length === 0
                ? 'Alle events'
                : events.length + (events.length === 1 ? ' valgt' : ' valgte'));
            $counter.toggleClass('is-active', events.length > 0);
        }
    }

    $(document).on('change', '.eventit-event-checkbox, .eventit-category-checkbox, #eventit-choose-view-type, #eventit-choose-columns', eventitBuildShortcode);

    /* Search + past-events filter. Rows stay in the DOM so ticked boxes survive. */
    function eventitFilterEventRows() {
        var needle = ($('#eventit-event-search').val() || '').toLowerCase().trim();
        var showPast = $('#eventit-show-past').is(':checked');
        var visible = 0;

        $('.eventit-event-row').each(function () {
            var $row = $(this);
            var isPast = $row.data('past') === 1 || $row.data('past') === '1';
            var checked = $row.find('.eventit-event-checkbox').is(':checked');
            /* Always keep a ticked row visible, so a selection can never hide itself */
            var match = checked
                || ((showPast || !isPast) && (needle === '' || String($row.data('search')).indexOf(needle) !== -1));

            $row.toggle(match);
            if (match) {
                visible++;
            }
        });

        $('#eventit-no-hits').toggle(visible === 0);
    }

    $('#eventit-event-search').on('input', eventitFilterEventRows);
    $('#eventit-show-past').on('change', eventitFilterEventRows);
    $(document).on('change', '.eventit-event-checkbox', eventitFilterEventRows);

    $('.eventit-pick-none').on('click', function (e) {
        e.preventDefault();
        $('.eventit-event-checkbox:checked').prop('checked', false);
        eventitBuildShortcode();
        eventitFilterEventRows();
    });

    eventitFilterEventRows();
    eventitBuildShortcode();

    /* Copy shortcode to clipboard */
    $('.eventit-copy-shortcode').on('click', function (e) {
        e.preventDefault();
        var text = $('#eventit-show-shortcode').text();
        var $feedback = $(this).siblings('.eventit-copy-feedback');
        var showFeedback = function () {
            $feedback.show();
            setTimeout(function () { $feedback.fadeOut(); }, 2000);
        };

        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(text).then(showFeedback);
        } else {
            var $tmp = $('<textarea>').val(text).appendTo('body');
            $tmp[0].select();
            document.execCommand('copy');
            $tmp.remove();
            showFeedback();
        }
    });

});
