(function () {
    'use strict';

    var SVG_NS = 'http://www.w3.org/2000/svg';
    var VIEWBOX = { width: 3000, height: 2000 };
    var HSL_PATTERN = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/;

    function randomInt(max) {
        return Math.floor(Math.random() * max);
    }

    function toRgbChannels(hsl) {
        var match = hsl.match(HSL_PATTERN);
        if (!match) {
            return null;
        }

        var h = parseInt(match[1], 10) / 360;
        var s = parseInt(match[2], 10) / 100;
        var l = parseInt(match[3], 10) / 100;

        function hueToRgb(p, q, t) {
            if (t < 0) t += 1;
            if (t > 1) t -= 1;
            if (t < 1 / 6) return p + (q - p) * 6 * t;
            if (t < 1 / 2) return q;
            if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
            return p;
        }

        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        var p = 2 * l - q;

        return {
            r: Math.round(hueToRgb(p, q, h + 1 / 3) * 255),
            g: Math.round(hueToRgb(p, q, h) * 255),
            b: Math.round(hueToRgb(p, q, h - 1 / 3) * 255)
        };
    }

    function hslToRgba(hsl) {
        var rgb = toRgbChannels(hsl);
        if (!rgb) {
            return 'rgba(0,0,0,1)';
        }

        return 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',1)';
    }

    function hslToHex(hsl) {
        var rgb = toRgbChannels(hsl);
        if (!rgb) {
            return '#26004d';
        }

        return '#' + ((1 << 24) + (rgb.r << 16) + (rgb.g << 8) + rgb.b).toString(16).slice(1);
    }

    function createSvgElement(tagName) {
        return document.createElementNS(SVG_NS, tagName);
    }

    function createGenerator() {
        function randomPosition() {
            return {
                cx: randomInt(100) + '%',
                cy: randomInt(100) + '%'
            };
        }

        function randomColorHsl() {
            var accentHues = [188, 202, 214, 332, 24, 42];
            var hue = accentHues[randomInt(accentHues.length)];
            var saturation = 62 + Math.random() * 18;
            var lightness = 48 + Math.random() * 14;
            return 'hsl(' + hue + ', ' + saturation + '%, ' + lightness + '%)';
        }

        function backgroundHex() {
            var darkHues = [206, 218, 228, 246];
            var hue = darkHues[randomInt(darkHues.length)];
            var saturation = 32 + Math.random() * 16;
            var lightness = 16 + Math.random() * 10;
            return hslToHex('hsl(' + hue + ', ' + saturation + '%, ' + lightness + '%)');
        }

        function buildGradient(defs, index) {
            var gradient = createSvgElement('radialGradient');
            var gradId = 'grad' + index;
            var position = randomPosition();
            var rgba = hslToRgba(randomColorHsl());

            gradient.setAttribute('id', gradId);
            gradient.setAttribute('cx', position.cx);
            gradient.setAttribute('cy', position.cy);
            gradient.setAttribute('r', '100%');
            gradient.setAttribute('fx', position.cx);
            gradient.setAttribute('fy', position.cy);
            gradient.setAttribute('gradientUnits', 'objectBoundingBox');

            var stopSolid = createSvgElement('stop');
            stopSolid.setAttribute('offset', '0');
            stopSolid.setAttribute('stop-color', rgba);
            stopSolid.setAttribute('stop-opacity', '1');

            var stopFade = createSvgElement('stop');
            stopFade.setAttribute('offset', '0.62');
            stopFade.setAttribute('stop-color', rgba.replace('1)', '0)'));
            stopFade.setAttribute('stop-opacity', '0');

            gradient.appendChild(stopSolid);
            gradient.appendChild(stopFade);
            defs.appendChild(gradient);

            return gradId;
        }

        function buildRect(fillValue) {
            var rect = createSvgElement('rect');
            rect.setAttribute('x', '0');
            rect.setAttribute('y', '0');
            rect.setAttribute('width', String(VIEWBOX.width));
            rect.setAttribute('height', String(VIEWBOX.height));
            rect.setAttribute('fill', fillValue);
            return rect;
        }

        return {
            generateRandomSvg: function (layerCount) {
                var totalLayers = typeof layerCount === 'number' ? layerCount : 7;
                var svg = createSvgElement('svg');
                var defs = createSvgElement('defs');
                var gradIds = [];

                svg.setAttribute('viewBox', '0 0 ' + VIEWBOX.width + ' ' + VIEWBOX.height);
                svg.setAttribute('fill', 'none');
                svg.setAttribute('xmlns', SVG_NS);

                for (var i = 0; i < totalLayers; i += 1) {
                    gradIds.push(buildGradient(defs, i));
                }

                svg.appendChild(defs);
                svg.appendChild(buildRect(backgroundHex()));

                gradIds.forEach(function (id) {
                    svg.appendChild(buildRect('url(#' + id + ')'));
                });

                return svg;
            },
            svgToDataUrl: function (svg) {
                var serializer = new XMLSerializer();
                var svgString = serializer.serializeToString(svg);
                return 'data:image/svg+xml;base64,' + btoa(svgString);
            }
        };
    }

    function applyDynamicBackgrounds() {
        var generator = createGenerator();
        var cards = document.querySelectorAll('.post-card-image:not([style*="background-image"])');

        cards.forEach(function (card) {
            card.classList.remove('gradient-1', 'gradient-2', 'gradient-3', 'gradient-4', 'gradient-5', 'dynamic-bg-placeholder');

            var svg = generator.generateRandomSvg();
            var dataUrl = generator.svgToDataUrl(svg);

            card.style.backgroundImage = 'url(' + dataUrl + ')';
            card.style.backgroundSize = 'cover';
            card.style.backgroundPosition = 'center';

            card.classList.add('dynamic-bg-applied');
        });
    }

    document.addEventListener('DOMContentLoaded', applyDynamicBackgrounds);
    window.nxtEventPlannerApplyDynamicBackgrounds = applyDynamicBackgrounds;
})();
