(function () {
    var DEFAULT_ANDROID_URL =
        'https://play.google.com/store/apps/details?id=com.org.laluparty';
    var PREVIEW_IMAGES = [
        {
            src: './assets/carousel-home.webp',
            alt: 'Welcome to lalu preview',
        },
        {
            src: './assets/carousel-voice-room.webp',
            alt: 'Meet friends by voice preview',
        },
    ];
    var params = new URLSearchParams(window.location.search);
    var els = {
        avatar: document.getElementById('inviterAvatar'),
        name: document.getElementById('inviterName'),
        track: document.getElementById('previewTrack'),
        scroll: document.getElementById('previewScroll'),
        downloadButton: document.getElementById('downloadButton'),
        toast: document.getElementById('pageToast'),
    };

    function firstParam(names) {
        for (var i = 0; i < names.length; i += 1) {
            var value = String(params.get(names[i]) || '').trim();
            if (value) return value;
        }
        return '';
    }

    function isIOS() {
        return /iPad|iPhone|iPod/.test(window.navigator.userAgent);
    }

    function t(key, fallback) {
        if (window.HyAppI18n && window.HyAppI18n.t) {
            return window.HyAppI18n.t(key, fallback);
        }
        return fallback;
    }

    function showToast(message) {
        els.toast.textContent = message;
        els.toast.classList.add('show');
        window.clearTimeout(showToast.timer);
        showToast.timer = window.setTimeout(function () {
            els.toast.classList.remove('show');
        }, 1800);
    }

    function resolveDownloadURL() {
        var commonURL = firstParam(['downloadUrl', 'download_url', 'url']);
        var iosURL = firstParam(['iosUrl', 'ios_url']);
        var androidURL =
            firstParam(['androidUrl', 'android_url']) || DEFAULT_ANDROID_URL;
        if (commonURL) return commonURL;
        if (isIOS() && iosURL) return iosURL;
        return androidURL;
    }

    function inviteCode() {
        return firstParam([
            'invite_code',
            'inviteCode',
            'code',
            'invitationCode',
        ]);
    }

    function setInviteCodeParams(searchParams, code) {
        searchParams.set('invite_code', code);
        searchParams.set('inviteCode', code);
        searchParams.set('code', code);
    }

    function setPlayInstallReferrer(searchParams, code) {
        searchParams.set('invite_code', code);
        searchParams.set('source', 'invite_h5');
    }

    function removeTopLevelInviteCodeParams(searchParams) {
        ['invite_code', 'inviteCode', 'code', 'invitationCode'].forEach(
            function (name) {
                searchParams.delete(name);
            }
        );
    }

    function buildDownloadURL(downloadURL, code) {
        var rawURL = String(downloadURL || '').trim();
        var normalizedCode = String(code || '').trim();
        if (!rawURL || !normalizedCode) return rawURL;

        try {
            var url = new URL(rawURL, window.location.href);
            if (url.hostname.indexOf('play.google.com') >= 0) {
                var referrer = new URLSearchParams(
                    url.searchParams.get('referrer') || ''
                );
                setPlayInstallReferrer(referrer, normalizedCode);
                removeTopLevelInviteCodeParams(url.searchParams);
                url.searchParams.set('referrer', referrer.toString());
                return url.toString();
            }

            setInviteCodeParams(url.searchParams, normalizedCode);
            return url.toString();
        } catch (error) {
            var separator = rawURL.indexOf('?') >= 0 ? '&' : '?';
            var params = new URLSearchParams();
            setInviteCodeParams(params, normalizedCode);
            return rawURL + separator + params.toString();
        }
    }

    function renderProfile() {
        var name = firstParam(['name', 'nickname', 'inviterName', 'userName']);
        var avatar = firstParam([
            'avatar',
            'avatarUrl',
            'avatar_url',
            'head',
            'headUrl',
        ]);
        if (name) {
            els.name.textContent = name;
        }
        if (avatar) {
            els.avatar.src = avatar;
        }
    }

    function appendCard(image) {
        var card = document.createElement('article');
        var img = document.createElement('img');
        card.className = 'preview-card';
        img.src = image.src;
        img.alt = image.alt;
        card.appendChild(img);
        els.track.appendChild(card);
    }

    function renderCarousel() {
        var loop = PREVIEW_IMAGES.concat(PREVIEW_IMAGES);
        loop.forEach(appendCard);
        window.requestAnimationFrame(function () {
            var half = els.track.scrollWidth / 2;
            if (half > 0) {
                els.track.style.setProperty('--loop-width', half + 'px');
            }
        });
    }

    function bindCarouselPause() {
        ['touchstart', 'pointerdown'].forEach(function (eventName) {
            els.scroll.addEventListener(eventName, function () {
                els.scroll.classList.add('is-dragging');
            });
        });
        ['touchend', 'touchcancel', 'pointerup', 'pointercancel'].forEach(
            function (eventName) {
                els.scroll.addEventListener(eventName, function () {
                    els.scroll.classList.remove('is-dragging');
                });
            }
        );
    }

    function openDownload() {
        var url = buildDownloadURL(resolveDownloadURL(), inviteCode());
        if (!url) {
            showToast(
                t(
                    'invite_landing.openDownloadFailed',
                    'Download URL is not configured.'
                )
            );
            return;
        }
        window.location.href = url;
    }

    function bindEvents() {
        els.downloadButton.addEventListener('click', openDownload);
        bindCarouselPause();
    }

    function init() {
        renderProfile();
        renderCarousel();
        bindEvents();
    }

    window.HyInviteLanding = {
        buildDownloadURL: buildDownloadURL,
    };

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
