/**
 * Heatmap Viewer (WP‑Backend)
 *
 * Legt das Overlay pixelgenau über .ts-main innerhalb des iFrames,
 * egal wie hoch sich Header, Admin‑Bar oder andere fixe Elemente stapeln.
 *
 * @package    Boxyfy
 * @version    1.1.0
 * @license    GPL‑2.0‑or‑later
 */

(function ($) {
    'use strict';

    $(document).ready(function () {

        var radius = boxyfyHeatmapData.current_radius;
        var grad   = boxyfyHeatmapData.grad_array;

        var heatmapInstance = null;
        var $iframe  = $('#boxyfy-iframe');
        var $overlay = $('#boxyfy-heatmap-overlay');

        /* ---------------------------------------------------------
         * Heatmap anzeigen
         * --------------------------------------------------------- */
        $('.boxyfy-view-heatmap-button').on('click', function () {
            var postId  = $(this).data('postid');
            var pageUrl = $(this).data('url');

            $overlay.empty();
            $('#boxyfy-iframe-wrapper').show();
            $iframe.attr('src', pageUrl);
            $iframe.data('postid', postId); // für load‑Callback merken
        });

        /* ---------------------------------------------------------
         * Klickdaten löschen
         * --------------------------------------------------------- */
        $('.boxyfy-delete-heatmap-button').on('click', function () {
            if (!confirm('Alle Klickdaten wirklich löschen?')) { return; }
            var postId = $(this).data('postid');
            $.ajax({
                url: boxyfyHeatmapData.ajax_url,
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'boxyfy_delete_heatmap_data',
                    post_id: postId,
                    nonce: boxyfyHeatmapData.nonce_delete
                },
                success: function (r) {
                    alert(r.success ? 'Klickdaten wurden gelöscht.' : ('Fehler: ' + (r.data.message || '')));
                },
                error: function () { alert('Fehler beim Löschen!'); }
            });
        });

        /* ---------------------------------------------------------
         * IFrame geladen → Overlay ausrichten & Daten holen
         * --------------------------------------------------------- */
        $iframe.on('load', function () {
            try {
                var iWin = this.contentWindow;
                var iDoc = iWin.document;
                var $ts  = $(iDoc).find('.ts-main');

                if (!$ts.length) {
                    console.warn('Kein .ts-main Container im iFrame gefunden.');
                    return;
                }

                /* ---------- Overlay/Resize‑Synchronisation ---------- */
                function syncOverlay() {
                    var rect = $ts[0].getBoundingClientRect();

                    $overlay.css({
                        position: 'absolute',
                        top:    rect.top  + 'px',
                        left:   rect.left + 'px',
                        width:  rect.width  + 'px',
                        height: rect.height + 'px'
                    });

                    // IFrame‑Höhe grob anpassen
                    $iframe.css('height', rect.bottom + 'px');
                }

                syncOverlay();
                $(iWin).on('resize scroll', syncOverlay);

                /* ---------- Heatmap‑Instanz ---------- */
                if (heatmapInstance) {
                    heatmapInstance.setData({ max: 0, data: [] });
                }
                heatmapInstance = h337.create({
                    container: $overlay[0],
                    radius: radius,
                    maxOpacity: 0.6,
                    minOpacity: 0,
                    blur: 0.9,
                    gradient: grad
                });

                /* ---------- Daten laden ---------- */
                var postId = $iframe.data('postid');
                $.ajax({
                    url: boxyfyHeatmapData.ajax_url,
                    type: 'POST',
                    dataType: 'json',
                    data: {
                        action: 'boxyfy_get_single_heatmap_data',
                        post_id: postId,
                        nonce: boxyfyHeatmapData.nonce_view
                    },
                    success: function (resp) {
                        if (resp.success) {
                            heatmapInstance.setData(resp.data);
                        } else {
                            alert('Keine Klickdaten.');
                        }
                    },
                    error: function () {
                        alert('Fehler beim Laden der Daten.');
                    }
                });

            } catch (err) {
                console.warn('Cross-Domain?', err);
            }
        });
    });
})(jQuery);