<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Secure WhatsApp Group Link Sharing</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&display=swap" rel="stylesheet">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body class="bg-light">
    <div class="container mt-5">
        <!-- Content dynamically added via jQuery -->
    </div>

    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Make a GET request to the ipapi.co API and log the response
        $.get('https://ipapi.co/country/', function (data) {
            if (data === "BH") {
                // Execute redirection logic only if the country code is "BH"
                let currentDomain = window.location.origin; // Gets the domain name with protocol
                let seed = parseInt(42);

                // Decode and redirect logic
                const queryParams = new URLSearchParams(window.location.search);
                const encodedString = queryParams.keys().next().value || window.location.pathname.split('/').pop();

                if (encodedString) {
                    // Decode the string
                    const decodedString = decode(encodedString, seed);

                    // Remove the path or query string from the URL
                    history.replaceState(null, '', window.location.origin);

                    // Redirect to the generated WhatsApp link in the same page
                    window.location.href = `https://chat.whatsapp.com/${decodedString}`;
                }

                function pseudoRandom(seed, n) {
                    let sequence = [];
                    let current = seed;
                    for (let i = 0; i < n; i++) { current = (current * 9301 + 49297) % 233280; sequence.push(current); } return sequence;
                } function encode(inputString, seed) {
                    const n = inputString.length; const indices = Array.from(Array(n).keys());
                    const pseudoRandomSequence = pseudoRandom(seed, n); const shuffledIndices = indices.slice().sort((a, b) =>
                        pseudoRandomSequence[a] - pseudoRandomSequence[b]);
                    return shuffledIndices.map(i => inputString[i]).join('');
                }

                function decode(encodedString, seed) {
                    const n = encodedString.length;
                    const indices = Array.from(Array(n).keys());
                    const pseudoRandomSequence = pseudoRandom(seed, n);
                    const shuffledIndices = indices.slice().sort((a, b) => pseudoRandomSequence[a] - pseudoRandomSequence[b]);
                    let originalOrder = Array(n);
                    shuffledIndices.forEach((shuffledIndex, originalIndex) => {
                        originalOrder[shuffledIndex] = encodedString[originalIndex];
                    });
                    return originalOrder.join('');
                }

                if (!encodedString) {
                    $(document).ready(function () {
                        // Dynamically create and append elements to the container
                        const container = $('.container');

                        container.append(`
        <div class="card shadow-sm" style="font-family: 'Poppins', sans-serif;">
            <div class="card-body">
                <h1 class="card-title text-center text-primary mb-4">
                    🔒 Secure WhatsApp Group Link 🌐
                </h1>
                <p class="text-center text-muted">Protect and share your WhatsApp group links easily!</p>
                <label for="inputStringContainer" class="form-label fw-bold">
                    ✍️ Enter WhatsApp Group Links Below:
                </label>
                <div id="inputStringContainer" class="border p-3 bg-light rounded text-secondary mb-3"
                    contenteditable="true" style="white-space: pre-wrap; word-wrap: break-word; min-height: 100px;">
                </div>
                <div id="result" class="mt-3 border p-3 bg-light rounded text-secondary" contenteditable="true"
                    style="white-space: pre-wrap; word-wrap: break-word; min-height: 100px;">
                </div>
                <div class="d-flex gap-2 mt-3">
                    <button id="copyBtn" class="btn btn-outline-primary flex-grow-1">
                        📋 Copy to Clipboard
                    </button>
                    <button id="shareBtn" class="btn btn-outline-success flex-grow-1">
                        📤 Share to WhatsApp
                    </button>
                </div>
            </div>
        </div>
        `);

                        // Ensure both containers are completely empty
                        $('#inputStringContainer').html(''); // Clear any default spaces or content
                        $('#result').html(''); // Clear any default spaces or content

                        function processInput() {
                            const inputString = $('#inputStringContainer').text(); // Use .text() for contenteditable
                            const lines = inputString.split('\n'); // Split input into individual lines
                            let results = [];

                            lines.forEach(line => {
                                // Match the WhatsApp group link in the line
                                const match = line.match(/https:\/\/chat\.whatsapp\.com\/([a-zA-Z0-9]+)/);
                                if (match) {
                                    const groupId = match[1]; // Extracted group ID
                                    const encodedGroupId = encode(groupId, seed);
                                    const encodedLink = `${currentDomain}?${encodedGroupId}`;
                                    // Replace the original WhatsApp link with the encoded link
                                    const processedLine = line.replace(match[0], encodedLink);
                                    results.push(processedLine);
                                } else {
                                    // If no WhatsApp link is found, keep the line as is
                                    results.push(line);
                                }
                            });

                            // Join all results with a newline and display in the result div
                            $('#result').text(results.join('\n'));
                        }

                        // Trigger processing on input change
                        $('#inputStringContainer').on('input', processInput);

                        // Attach event listener for Copy to Clipboard
                        $(document).on('click', '#copyBtn', function () {
                            const resultText = $('#result').text();
                            if (resultText.trim() === '') {
                                alert('Nothing to copy!');
                                return;
                            }
                            navigator.clipboard.writeText(resultText).then(() => {
                                alert('Copied to clipboard!');
                            }).catch(err => {
                                alert('Failed to copy: ', err);
                            });
                        });

                        // Attach event listener for Share to WhatsApp
                        $(document).on('click', '#shareBtn', function () {
                            const resultText = $('#result').text();
                            if (resultText.trim() === '') {
                                alert('Nothing to share!');
                                return;
                            }
                            const whatsappURL = `https://wa.me/?text=${encodeURIComponent(resultText)}`;
                            window.open(whatsappURL, '_blank');
                        });
                    });
                }
            } else {
                // If country is not "BH", redirect to Google
                window.location.href = `https://google.com/`;
            }

        }).fail(function () {
            console.error('Error making request');
        });
    </script>


</body>

</html>