@php

    $page_title = 'Live AI trading';
    $short_description = 'Watch live trading done by our trading bot as the execute these trades';

@endphp

@php

    use Illuminate\Support\Facades\DB;

    $transactions = DB::select("
    SELECT transactions.*, users.name AS username 
    FROM transactions 
    JOIN users ON users.id = transactions.user_id 
    ORDER BY transactions.id DESC 
    LIMIT 10
");

@endphp

{{-- layout --}}
@extends('templates.' . site('template') . '.layouts.front')


@section('css')
@endsection

@section('header')
    <!-- Hero Section -->
    <section class="relative overflow-hidden pt-16 md:pt-20 md:pb-12 px-6 lg:px-40 bg-[#2d2d2d]">
        <img src="{{ asset('/assets/templates/gopie/images/bg-object3-dark.png') }}"
            class="hidden md:block absolute top-1 right-1" alt="" />
        <img src="{{ asset('/assets/templates/gopie/images/bg-object4-dark.png') }}"
            class="hidden md:block absolute bottom-1 left-1" alt="" />
        <div class="px-4 py-16 md:py-24 text-center min-h-[60vh] items-center flex flex-col justify-center">
            <h1 class="text-white text-4xl md:text-5xl font-semibold leading-tight mb-6 pb-4">
                Live AI
                <span class="relative">Trading
                    <img src="{{ asset('/assets/templates/gopie/images/underline.png') }}" class="absolute right-1"
                        alt="" /></span>
            </h1>

            <p class="text-gray-400 text-lg mb-8 max-w-5xl mx-auto">
                {{ $short_description }}
            </p>
        </div>
    </section>
@endsection


@section('contents')
    <!-- trades section  -->
    <section class="px-6 lg:px-40 mt-12 md:mt-28">
        <!-- recent trades box -->
        <div
            class="w-full max-w-[95vw] mx-auto text-sm p-4 md:p-8 rounded-3xl shadow-[0px_10px_20px_0px_rgba(0,_0,_0,_0.15)]">
            <h2 class="text-sm mb-4 text-black">Recent Trades by {{ site('name') }}</h2>
            <div class="w-full px-2 md:px-10 mt-5 text-white">
                <div class="w-full">
                    <div class="w-full p-3">
                        <div class="w-full overflow-x-auto" id="recentTradesContainer">
                            <div class="w-full grid grid-cols-1 gap-4 mt-2 text-xs" id="recentTrades">
                                <!-- Initial trades will be populated here -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
@endsection

@section('scripts')
    {{-- recent trades table data --}}
    <script>
        // Initial trades data
        const initialTrades = @json(recentTradesAll());

        // Keep track of currently displayed trades
        let currentTrades = [];

        // trade element from data
        function createTradeElement(trade) {
            const div = document.createElement("div");
            const currentTime = new Date().toLocaleTimeString("en-US", {
                hour: "numeric",
                minute: "2-digit",
                second: "2-digit",
                hour12: true,
            });

            div.className = `recent-trade w-full p-4 flex justify-between items-center ${
            trade.profit.startsWith("+")
            ? "text-green-500 hover:bg-pink-400"
            : "text-red-500 hover:bg-pink-800"
            } shadow-md transition border-b border-gray-600`;

            div.innerHTML = `
              <p class="recent_trade_time text-sm w-24">${currentTime}</p>
              <p class="text-md w-28 px-4">${trade.country}</p>
            <p class="text-md w-28 px-4">${trade.exchange}</p>
            <p class="text-md w-28 px-4">${trade.bot}</p>
              <p class="text-sm w-28 px-4">${trade.pair}</p>
              <p class="text-sm w-32 text-right">${trade.amount}</p>
              <p class="text-sm w-20 text-right">${trade.profit}</p>
          `;

            return div;
        }

        // Update all trade times
        function updateTradeTimes() {
            const tradeTimeElements =
                document.querySelectorAll(".recent_trade_time");
            const currentTime = new Date().toLocaleTimeString("en-US", {
                hour: "numeric",
                minute: "2-digit",
                second: "2-digit",
                hour12: true,
            });
            tradeTimeElements.forEach((element) => {
                element.textContent = currentTime;
            });
        }

        // Shuffle and display trades
        function shuffleAndDisplayRecentTrades() {
            const tradesDiv = document.getElementById("recentTrades");
            if (!tradesDiv) return;

            // Initialize trades if needed
            if (currentTrades.length === 0) {
                currentTrades = initialTrades.map((trade) =>
                    createTradeElement(trade)
                );
            }

            // Create a copy and shuffle
            const shuffledTrades = [...currentTrades];
            for (let i = shuffledTrades.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [shuffledTrades[i], shuffledTrades[j]] = [
                    shuffledTrades[j],
                    shuffledTrades[i],
                ];
            }

            // Clear and display first 9 trades
            tradesDiv.innerHTML = "";
            const displayCount = Math.min(9, shuffledTrades.length);
            for (let i = 0; i < displayCount; i++) {
                tradesDiv.appendChild(shuffledTrades[i].cloneNode(true));
            }

            updateTradeTimes();
        }

        // Handle periodic updates
        function updateRecentTrades() {
            // In this version, we'll just reshuffle the existing trades
            // In a real implementation, you would fetch new data from the server
            shuffleAndDisplayRecentTrades();
        }

        // Initialize when document is ready
        document.addEventListener("DOMContentLoaded", function() {
            // Initial display
            shuffleAndDisplayRecentTrades();

            // Set up intervals
            const SHUFFLE_INTERVAL = 1000; // 1 second
            const UPDATE_INTERVAL = 10000; // 10 seconds

            // Clear any existing intervals
            if (window.shuffleInterval) clearInterval(window.shuffleInterval);
            if (window.updateInterval) clearInterval(window.updateInterval);

            // Set new intervals
            window.shuffleInterval = setInterval(
                shuffleAndDisplayRecentTrades,
                SHUFFLE_INTERVAL
            );
            window.updateInterval = setInterval(
                updateRecentTrades,
                UPDATE_INTERVAL
            );
        });

        // Clean up on page unload
        window.addEventListener("unload", function() {
            if (window.shuffleInterval) clearInterval(window.shuffleInterval);
            if (window.updateInterval) clearInterval(window.updateInterval);
        });
    </script>
@endsection
