@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="bg-[#f3feed] pt-8 md:pt-10 px-6">
        <div class="max-w-6xl mx-auto min-h-[600px] flex flex-col md:flex-row items-center">
            <!-- Text Content -->
            <div class="md:w-1/2 flex flex-col justify-center text-left h-full">
                <h1 class="text-3xl md:text-5xl font-bold text-gray-900">
                    Live AI Trading
                </h1>
                <p class="text-gray-700 mt-4 text-sm md:text-base max-w-lg">
                    We offer a diverse range of portfolio options for our advanced
                    trading bots, ensuring that there is a plan tailored to suit every
                    budget and investment preference. Explore our selection and choose
                    the option that best aligns with your financial goals and comfort
                    level.
                </p>
                <!-- auth  -->
                <div class="flex space-x-4 md:gap-8 mt-8">
                    @if (user())
                        <a href="{{ route('user.dashboard') }}" class="gradient-bg px-12 py-2 rounded-4xl text-black">
                            Dashboard
                        </a>
                    @else
                        <a href="{{ route('user.login') }}" class="gradient-bg px-12 py-2 rounded-4xl text-black">
                            Sign In
                        </a>
                        <a href="{{ route('user.register') }}" class="gradient-border4 px-12 py-2 rounded-4xl">
                            Sign up
                        </a>
                    @endif
                </div>
            </div>

            <!-- Image Content -->
            <div class="md:w-1/2 flex justify-end items-center mt-6 md:mt-0">
                <img src="{{ asset('/assets/templates/lunex/images/live-ai-trades-hero.png') }}" alt="AI Robot"
                    class="max-w-full h-auto md:max-h-[500px]" />
            </div>
        </div>
    </section>
@endsection


@section('contents')
    <!-- trade from anywhere section  -->
    <section class="pt-8 md:pt-20 px-6 md:px-20 lg:px-40">
        <h2 class="text-black font-bold text-2xl md:text-3xl lg:text-4xl text-center mt-4 md:mt-6">
            Trade From Anywhere
        </h2>

        <p class="text-black text-lg text-center leading-8 mt-4 md:mt-6 mb-4 md:mb-6">
            Whether you're at home or on the go, seize market opportunities anytime,
            anywhere, and secure your financial future effortlessly. Trade from any
            and every city.
        </p>

        <div class="relative w-full  md:h-[600px] md:mt-20" style="height:80vh;">
            <!-- Container for all semicircles -->
            <div class="absolute inset-0 md:flex flex-col items-center">
                <!-- First semicircle (largest, back) -->
                <div class="absolute w-full max-w-[700px] mx-auto hidden md:block">
                    <img src="{{ asset('/assets/templates/lunex/images/semi-circle1.svg') }}" alt="First semicircle"
                        class="w-full h-auto" />
                </div>

                <!-- Second semicircle (middle) -->
                <div class="absolute w-full max-w-[600px] mx-auto top-8 hidden md:block">
                    <img src="{{ asset('/assets/templates/lunex/images/semi-circle2.svg') }}" alt="Second semicircle"
                        class="w-full h-auto" />
                </div>

                <!-- Third semicircle (smallest, front) -->
                <div class="absolute w-full max-w-[500px] mx-auto top-16 hidden md:block">
                    <img src="{{ asset('/assets/templates/lunex/images/semi-circle3.svg') }}" alt="Third semicircle"
                        class="w-full h-auto" />
                </div>

                <!-- recent trades box -->
                <div
                    class="absolute w-full max-w-[800px] mx-auto top-[20%] border text-sm gradient-border-text-recent-trades p-4 md:p-8 rounded-3xl">
                    <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" style="max-height: 600px;">
                                    <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>
            </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
