/**
 * ITSWEBER CMS – Social Embed Section Plugin
 * Frontend JavaScript for consent-aware lazy loading of social embeds.
 *
 * Behaviour:
 *   1. On page load, checks if consent module is active (data-ses-consent attribute).
 *   2. If consent is NOT required (no consent module): loads all embeds immediately.
 *   3. If consent IS required: shows placeholders with "Load Content" buttons.
 *      - Individual button clicks: load that single embed.
 *      - Consent granted via CMS banner: auto-loads all pending embeds.
 *   4. Provider SDK scripts (TikTok embed.js, Instagram embed.js) are loaded once
 *      on demand – not eagerly – to avoid unnecessary external requests.
 *
 * Provider SDK registry:
 *   - TikTok:   https://www.tiktok.com/embed.js
 *   - Instagram: https://www.instagram.com/embed.js
 *   - YouTube:   No extra SDK needed (iframe-based)
 */
(function () {
    'use strict';

    // Track which provider SDKs have been loaded
    var loadedSDKs = {};

    /**
     * Check if the CMS consent module has granted 'functional' consent.
     * Falls back to true if no consent module is present (consent not required).
     */
    function hasConsent() {
        // Check the CMS consent cookie directly (iw_consent JSON cookie)
        try {
            var cookieMatch = document.cookie.match(/(?:^|;\s*)iw_consent=([^;]*)/);
            if (cookieMatch) {
                var consent = JSON.parse(decodeURIComponent(cookieMatch[1]));
                return consent && consent.functional === true;
            }
        } catch (e) {
            // Cookie parse error – fall through
        }

        // Check if window.iwConsentGiven exists (alternative API)
        if (typeof window.iwConsentGiven === 'function') {
            return window.iwConsentGiven('functional');
        }

        // No consent module detected – allow embeds
        return true;
    }

    /**
     * Load a provider SDK script (once per provider).
     */
    function loadSDK(provider) {
        if (loadedSDKs[provider]) return;
        loadedSDKs[provider] = true;

        var src;
        switch (provider) {
            case 'tiktok':
                src = 'https://www.tiktok.com/embed.js';
                break;
            case 'instagram':
                src = 'https://www.instagram.com/embed.js';
                break;
            default:
                return; // YouTube uses iframes, no SDK needed
        }

        var script = document.createElement('script');
        script.src = src;
        script.async = true;
        document.body.appendChild(script);
    }

    /**
     * Activate a single embed: replace placeholder with actual embed content.
     */
    function activateEmbed(wrap) {
        if (wrap.getAttribute('data-ses-embed') === 'loaded') return;

        var template = wrap.querySelector('.ses-embed-template');
        if (!template) return;

        // Clone template content and insert into wrapper
        var content = template.content.cloneNode(true);
        wrap.appendChild(content);
        wrap.setAttribute('data-ses-embed', 'loaded');

        // Determine provider and load SDK if needed
        var item = wrap.closest('.ses-item');
        if (item) {
            var provider = item.getAttribute('data-ses-provider');
            if (provider) {
                loadSDK(provider);

                // TikTok: re-process embeds after inserting
                if (provider === 'tiktok' && window.tiktokEmbed && typeof window.tiktokEmbed.process === 'function') {
                    window.tiktokEmbed.process();
                }

                // Instagram: re-process embeds after inserting
                if (provider === 'instagram' && window.instgrm && typeof window.instgrm.Embeds.process === 'function') {
                    window.instgrm.Embeds.process();
                }
            }
        }
    }

    /**
     * Activate all pending embeds in a section.
     */
    function activateAllInSection(section) {
        var wraps = section.querySelectorAll('.ses-embed-wrap[data-ses-embed="pending"]');
        wraps.forEach(activateEmbed);
    }

    /**
     * Initialize all social embed sections on the page.
     */
    function init() {
        var sections = document.querySelectorAll('.social-embed-section');
        if (!sections.length) return;

        sections.forEach(function (section) {
            var consentRequired = section.hasAttribute('data-ses-consent');

            if (!consentRequired || hasConsent()) {
                // No consent needed or already granted: activate all immediately
                activateAllInSection(section);
            } else {
                // Consent required but not yet granted: bind click handlers on placeholders
                var buttons = section.querySelectorAll('.ses-consent-btn');
                buttons.forEach(function (btn) {
                    btn.addEventListener('click', function (e) {
                        e.preventDefault();
                        var wrap = btn.closest('.ses-embed-wrap');
                        if (wrap) {
                            activateEmbed(wrap);
                        }
                    });
                });
            }
        });
    }

    // Listen for consent changes (CMS consent banner fires a custom event)
    document.addEventListener('iw:consent-updated', function () {
        if (hasConsent()) {
            var sections = document.querySelectorAll('.social-embed-section[data-ses-consent]');
            sections.forEach(activateAllInSection);
        }
    });

    // Initialize on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
