<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interaction Comparison</title>
    <style>
        #count {
            display: inline-block;
            min-width: 24px;
            height: 24px;
            line-height: 24px;
            text-align: center;
            background-color: blue;
            color: white;
            border-radius: 50%;
            font-weight: bold;
            text-decoration: none;
        }

        #debug {
            font-family: monospace;
            font-size: 0px;
            color: #333;
            margin-top: 20px;
            //background: #f0f0f0;
            padding: 0px;
            border-radius: 0px;
            border: 0px solid #ddd;
        }

        pre {
            margin: 0;
        }

        .item {
            margin: 15px 0;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: white; /* Default background color */
        }

        .header {
            font-weight: bold;
        }

        .actor, .object, .url, .content, .reply {
            margin: 5px 0;
        }

        .like {
            background-color: pink !important; /* Pink for Likes */
        }

        .reply {
            background-color: lightblue !important; /* Light blue for Replies */
        }

        .boost {
            background-color: white !important; /* White for other interactions */
        }

        /* Invisible div to store the content */
        #invisibleContent {
            display: none;
        }
    </style>
</head>
<body>
    <a id="count" href="#" style="display:inline-block; min-width:24px; height:24px; line-height:24px; text-align:center; background-color: blue; color:white; border-radius:50%; font-weight:bold; text-decoration:none;">Loading...</a>
    
    <div id="debug">
        <h3>Debugging Information:</h3>
        <pre id="debugContent">Loading data...</pre>
    </div>

    <!-- Invisible div to hold the rendered content -->
    <div id="invisibleContent"></div>

    <script>
        // Base URLs for fetching data
        const baseUrlTxt = 'https://alceawis.com/interactionlatest.txt';
        const baseUrlJson = 'https://alceawis.com/interaction.json';

        // Function to fetch the .txt and .json files with cache-busting
        async function fetchData() {
            try {
                // Append timestamp to the URL to bypass cache
                const timestamp = new Date().getTime();
                const txtUrl = `${baseUrlTxt}?t=${timestamp}`;
                const jsonUrl = `${baseUrlJson}?t=${timestamp}`;

                const txtResponse = await fetch(txtUrl);
                const jsonResponse = await fetch(jsonUrl);
                
                if (!txtResponse.ok || !jsonResponse.ok) {
                    throw new Error("Error fetching the files");
                }

                const txtData = await txtResponse.text();
                const jsonData = await jsonResponse.json();

                return { txtData, jsonData };
            } catch (error) {
                console.error(error);
                document.getElementById('debugContent').textContent = `Error fetching data: ${error.message}`;
                return { txtData: '', jsonData: [] };
            }
        }

        // Function to parse the .txt file and get the latest timestamp
        function parseTxtData(txtData) {
            const lines = txtData.split('\n');
            let latestTimestamp = '';

            for (let line of lines) {
                const match = line.match(/"received_at": "(.*?)"/);
                if (match) {
                    latestTimestamp = match[1].trim();
                    break;
                }
            }
            return latestTimestamp;
        }

        // Function to compare the .txt timestamp with the received_at in the .json
        function compareTimestamps(jsonData, txtTimestamp) {
            let newInteractionsCount = 0;
            let newInteractions = [];

            jsonData.forEach(interaction => {
                const receivedAt = interaction.received_at;

                if (receivedAt && receivedAt > txtTimestamp) {
                    newInteractionsCount++;
                    newInteractions.push(interaction);
                }
            });

            return { newInteractionsCount, newInteractions };
        }

        // Function to render data and place it into the invisible div
        function renderData(data) {
            const invisibleContent = document.getElementById('invisibleContent');
            invisibleContent.innerHTML = ''; // Clear previous content

            if (!Array.isArray(data)) {
                invisibleContent.textContent = 'JSON root is not an array.';
                return;
            }

            data.slice().reverse().forEach(item => {
                const div = document.createElement('div');
                div.classList.add('item');

                // Apply background colors based on interaction type
                if (item.type === 'Like') {
                    div.classList.add('like');  // Apply pink background
                } else if (item.type === 'Create' && item.object && item.object.inReplyTo) {
                    div.classList.add('reply');  // Apply light blue background for replies
                } else {
                    div.classList.add('boost');  // Default white background for other interactions
                }

                const header = document.createElement('div');
                header.classList.add('header');
                header.textContent = `${item.type} - ${new Date(item.published).toLocaleString()}`;
                div.appendChild(header);

                const actorDiv = document.createElement('div');
                actorDiv.classList.add('actor');
                actorDiv.innerHTML = `Actor: <a href="${item.actor}" target="_blank">${item.actor}</a>`;
                div.appendChild(actorDiv);

                if (item.type === 'Like') {
                    const objLink = createLink(item.object, 'Liked Object');
                    const objDiv = document.createElement('div');
                    objDiv.classList.add('object');
                    objDiv.innerHTML = `Object: <a href="${item.object}" target="_blank">${item.object}</a>`;
                    div.appendChild(objDiv);
                } else if (item.type === 'Create') {
                    const obj = item.object;
                    if (obj) {
                        if (obj.url) {
                            const urlDiv = document.createElement('div');
                            urlDiv.classList.add('url');
                            urlDiv.innerHTML = `URL: <a href="${obj.url}" target="_blank">${obj.url}</a>`;
                            div.appendChild(urlDiv);
                        }

                        if (obj.content) {
                            const contentDiv = document.createElement('div');
                            contentDiv.classList.add('content');
                            contentDiv.innerHTML = `Content: ${obj.content}`;
                            div.appendChild(contentDiv);
                        }

                        if (obj.inReplyTo) {
                            const replyDiv = document.createElement('div');
                            replyDiv.classList.add('reply');
                            replyDiv.innerHTML = `In Reply To: <a href="${obj.inReplyTo}" target="_blank">${obj.inReplyTo}</a>`;
                            div.appendChild(replyDiv);
                        }
                    }
                }

                invisibleContent.appendChild(div);
            });
        }

        // Function to create a link element
        function createLink(url, text) {
            const a = document.createElement('a');
            a.href = url;
            a.target = "_blank";
            a.rel = "noopener noreferrer";
            a.textContent = text || url;
            return a;
        }

        // Function to display the badge with the number of new interactions
        function displayBadge(newCount, newInteractions) {
            const badgeLink = document.getElementById('count');
            
            if (newCount > 0) {
                badgeLink.textContent = newCount;
                badgeLink.style.backgroundColor = 'blue';

                badgeLink.addEventListener('click', function (event) {
                    event.preventDefault();
                    openNewTabWithInteractions();
                });
            } else {
                badgeLink.textContent = '0';
                badgeLink.style.backgroundColor = 'gray';
            }
        }

        // Function to open a new tab with the invisible content and its styles
        function openNewTabWithInteractions() {
            const newTab = window.open('', '_blank');
            newTab.document.write('<html><head><title>New Interactions</title>');
            
            // Inject the necessary styles into the new tab's head
            newTab.document.write(`
                <style>
                    .item { margin: 15px 0; padding: 10px; border: 1px solid #ddd; border-radius: 5px; background-color: white; }
                    .like { background-color: pink; }
                    .reply { background-color: lightblue; }
                    .boost { background-color: white; }
                    .header { font-weight: bold; }
                    .actor, .object, .url, .content, .reply { margin: 5px 0; }
                </style>
            `);
            
            newTab.document.write('</head><body>');
            newTab.document.write('<h1>New Interactions</h1>');

            // Copy the content of the invisible div to the new tab
            const content = document.getElementById('invisibleContent').innerHTML;
            newTab.document.write(content);
            newTab.document.write('<br><a target="_blank" href="https://alceawis.com/reportinteraction.php" style=color:transparent>ReFetch</a>');

            newTab.document.write('</body></html>');
            newTab.document.close();
        }

        // Main function to compare the .txt and .json files and display the results
        async function compareInteractions() {
            const { txtData, jsonData } = await fetchData();
            const txtTimestamp = parseTxtData(txtData);

            if (!txtTimestamp) {
                document.getElementById('debugContent').textContent = 'Invalid or empty timestamp in .txt file.';
                return;
            }

            const { newInteractionsCount, newInteractions } = compareTimestamps(jsonData, txtTimestamp);

            document.getElementById('debugContent').textContent = `Total New Interactions: ${newInteractionsCount}`;
            displayBadge(newInteractionsCount, newInteractions);
            renderData(newInteractions);
        }

        // Trigger the comparison when the page loads
        window.onload = compareInteractions;
    </script>
</body>
</html>


<!---Fedi-Acripub--Interacrion-Gather-->
<!--<?php
// Path to your interaction.json file
$jsonFilePath = 'interaction.json';
$outputFilePath = 'interactionlatest.txt';

// Check if the file exists
if (!file_exists($jsonFilePath)) {
    die("File not found: $jsonFilePath");
}

// Read and decode the JSON data
$jsonData = file_get_contents($jsonFilePath);
$interactions = json_decode($jsonData, true);

// Check if JSON data is valid
if ($interactions === null) {
    die("Error decoding JSON data");
}

// Initialize variables to keep track of the newest interaction
$newestInteraction = null;
$newestPublished = null;

// Loop through all interactions
foreach ($interactions as $interaction) {
    // Convert the 'published' date to a DateTime object for comparison
    $publishedDate = new DateTime($interaction['published']);

    // Update the newest interaction if this one is newer
    if ($newestPublished === null || $publishedDate > $newestPublished) {
        $newestInteraction = $interaction;
        $newestPublished = $publishedDate;
    }
}

// Check if a newest interaction was found
if ($newestInteraction !== null) {
    // Convert the newest interaction to a readable format (You can customize this format as needed)
    $newestInteractionText = json_encode($newestInteraction, JSON_PRETTY_PRINT);

    // Write the newest interaction to the output file
    file_put_contents($outputFilePath, $newestInteractionText);

    echo "Newest interaction written to $outputFilePath\n";
} else {
    echo "No interactions found.\n";
}
?>->
