/**
 * Shois Chat Button — Platform Links
 *
 * Builds chat URLs for each platform with deep link support
 * and mobile detection.
 *
 * @package ShoisChatButton
 */
(function () {
    'use strict';

    /**
     * Detect if the user is on a mobile device.
     *
     * @return {boolean}
     */
    function isMobile() {
        return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
            navigator.userAgent
        );
    }

    /**
     * Clean a contact value based on input type.
     *
     * @param {string} inputType The platform's input type.
     * @param {string} value     Raw contact value.
     * @return {string} Cleaned value.
     */
    function cleanValue(inputType, value) {
        var cleaned = (value || '').trim();

        switch (inputType) {
            case 'phone':
                // Remove spaces, dashes, parentheses. Keep + and digits.
                cleaned = cleaned.replace(/[^+0-9]/g, '');
                // Strip leading zero — wa.me and other phone APIs require
                // international format without leading 0.
                if (cleaned.charAt(0) !== '+' && cleaned.charAt(0) === '0') {
                    cleaned = cleaned.substring(1);
                }
                break;
            case 'username':
                cleaned = cleaned.replace(/^@/, '');
                break;
            default:
                break;
        }

        return cleaned;
    }

    /**
     * Resolve dynamic variables in a message string.
     *
     * @param {string} message  Message with {variable} placeholders.
     * @param {Object} vars     Variable values from shcb_config.
     * @return {string} Message with variables replaced.
     */
    function resolveVariables(message, vars) {
        if (!message || !vars) {
            return message || '';
        }

        return message.replace(/\{(\w+)\}/g, function (match, key) {
            return vars.hasOwnProperty(key) ? vars[key] : match;
        });
    }

    /**
     * Build a platform chat URL.
     *
     * @param {Object} platform Platform definition object.
     * @param {string} value    Contact value (phone/username/URL).
     * @param {string} message  Pre-filled message.
     * @param {Object} vars     Dynamic variables for message resolution.
     * @return {string} Generated URL.
     */
    function buildPlatformLink(platform, value, message, vars) {
        var cleaned = cleanValue(platform.input_type, value);
        var resolvedMsg = resolveVariables(message, vars);
        var encodedMsg = encodeURIComponent(resolvedMsg);
        var mobile = isMobile();
        var url;

        // Use deep link on mobile if available.
        if (mobile && platform.mobile_deep_link) {
            url = platform.mobile_deep_link;
        } else {
            url = platform.link_format;
        }

        if (!url) {
            return '';
        }

        // v1.1.1: Ensure we don't open URLs with placeholder strings or empty values.
        if (!cleaned || cleaned === '{value}' || cleaned === '/value' || cleaned === 'value') {
            return '';
        }

        url = url.replace(/\{value\}/g, encodeURIComponent(cleaned));

        if (platform.supports_pre_message && resolvedMsg) {
            url = url.replace(/\{message\}/g, encodedMsg);
        } else {
            url = url.replace(/[?&]text=\{message\}/g, '');
            url = url.replace(/\{message\}/g, '');
        }

        return url;
    }

    /**
     * Open a platform link with deep link fallback.
     *
     * On mobile, tries app deep link first. If the app is not installed
     * (page stays visible after 1800ms), falls back to web URL.
     *
     * @param {Object}  platform Platform definition.
     * @param {string}  value    Contact value.
     * @param {string}  message  Pre-filled message.
     * @param {Object}  vars     Dynamic variables.
     * @param {boolean} newTab   Whether to open in a new tab.
     */
    function openPlatformLink(platform, value, message, vars, newTab) {
        var url = buildPlatformLink(platform, value, message, vars);
        var mobile = isMobile();
        var target = newTab ? '_blank' : '_self';

        if (!url) {
            return;
        }

        // On mobile with deep link: try deep link with web fallback.
        if (mobile && platform.mobile_deep_link) {
            var webUrl = platform.link_format
                ? platform.link_format
                    .replace('{value}', encodeURIComponent(cleanValue(platform.input_type, value)))
                    .replace(/[?&]text=\{message\}/g, '')
                    .replace('{message}', '')
                : '';

            // Attempt deep link.
            var hidden = false;
            var onVisibility = function () {
                if (document.hidden) {
                    hidden = true;
                }
            };

            document.addEventListener('visibilitychange', onVisibility);

            // Create temporary link and click it.
            var link = document.createElement('a');
            link.href = url;
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();

            // After 1800ms, if page is still visible, app not installed. Fallback.
            setTimeout(function () {
                document.removeEventListener('visibilitychange', onVisibility);
                document.body.removeChild(link);

                if (!hidden && webUrl) {
                    window.open(webUrl, target, 'noopener,noreferrer');
                }
            }, 1800);

            return;
        }

        // Standard link open.
        window.open(url, target, 'noopener,noreferrer');
    }

    // Export to global scope for widget.js.
    window.SCBPlatformLinks = {
        build: buildPlatformLink,
        open: openPlatformLink,
        isMobile: isMobile,
        cleanValue: cleanValue,
        resolveVariables: resolveVariables,
    };
})();
