<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Livewire\Attributes\Layout;
use App\Models\Kyc;
use App\Models\Deposit;
use App\Models\Withdrawal;
use App\Models\WalletReserve;
use App\Models\User;
use App\Models\Account;
use App\Models\Loan;
use App\Models\LoanInstallment;
use App\Models\UserLogin;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;
use App\Models\Transaction;

new #[Layout('layouts::base', ['title' => 'Admin Dashboard'])] class extends Component {
    public array $cardStats = [];
    public $usersByCountry;
    public $usersByBrowser;
    public array $newUsersTrend = [];
    public array $pendingActions = [];
    public $topUsersByBalance;

    public array $loanStats = [];
    public $pendingLoans;
    public $approvedLoans;
    public $overdueLoans;
    public $completedLoans;
    public $totalLoanAmount;
    public $totalOutstanding;
    public array $loanTrendDates = [];
    public array $loanDisbursementsTrend = [];
    public array $loanRepaymentsTrend = [];
    public array $loanOverdueTrend = [];

    public array $depositTrend = [];
    public array $withdrawTrend = [];
    public array|Collection $recentTransactions;

    private $admin;

    public function mount(): void
    {
        $this->admin = auth('admin')->user();
        $this->loadDashboardData();
    }

    /** ================= CENTRAL ADMIN QUERY HELPER ================= */
    private function adminQuery(\Illuminate\Database\Eloquent\Builder $query)
    {
        if ($this->admin) {
            return $query->visibleToAdmin($this->admin);
        }
        return $query->whereRaw('1 = 0'); // deny access if no admin
    }

    /** ================= LOAD DASHBOARD ================= */
    protected function loadDashboardData(): void
    {
        $this->loadUserStats();
        $this->loadUserTrends();
        $this->loadPendingActions();
        $this->loadTopUsers();
        $this->loadDepositsAndWithdrawals();
        $this->loadBalances();
        $this->loadKYCStats();
        $this->loadReferralStats();
        $this->loadLoanStats();
        $this->loadLoanTrends();
        $this->loadDashboardCards();
        $this->loadRecentTransactions();
    }

    /** ================= USERS ================= */
    private function loadUserStats(): void
    {
        $this->totalUsers = $this->adminQuery(User::query())->count();
        $this->newUsers7d = $this->adminQuery(User::query())
            ->where('created_at', '>=', now()->subDays(7))
            ->count();

        $this->activeUsers7d = $this->adminQuery(UserLogin::query())
            ->where('created_at', '>=', now()->subDays(7))
            ->distinct('user_id')
            ->count();

        $this->usersByCountry = $this->adminQuery(UserLogin::query())->selectRaw('location, COUNT(*) as count')->whereNotNull('location')->groupBy('location')->get();

        $this->usersByBrowser = $this->adminQuery(UserLogin::query())->selectRaw('browser, COUNT(*) as count')->whereNotNull('browser')->groupBy('browser')->get();
    }

    /** ================= LOAN STATS ================= */
    private function loadLoanStats(): void
    {
        $this->pendingLoans = $this->adminQuery(Loan::query()->pending())->count();
        $this->approvedLoans = $this->adminQuery(Loan::query()->approved())->count();
        $this->overdueLoans = $this->adminQuery(Loan::query()->overdue())->count();
        $this->completedLoans = $this->adminQuery(Loan::query()->completed())->count();

        $this->totalLoanAmount = $this->adminQuery(Loan::query()->approved())->sum('amount');

        $this->totalOutstanding = $this->adminQuery(Loan::query())
            ->whereIn('status', ['pending', 'approved', 'overdue'])
            ->get()
            ->sum(fn($loan) => (float) $loan->remaining_balance);

        $this->loanStats = [$this->card('clock', $this->pendingLoans, 'Pending Loans'), $this->card('check', $this->approvedLoans, 'Loan Disbursements'), $this->card('exclamation-circle', $this->overdueLoans, 'Overdue Loans'), $this->card('check-circle', $this->completedLoans, 'Completed Loans'), $this->card('building-office-2', $this->totalLoanAmount, 'Total Loan Amount', true), $this->card('wallet', $this->totalOutstanding, 'Total Outstanding', true)];
    }

    /** ================= TRENDS ================= */
    private function loadUserTrends(): void
    {
        $this->depositTrend = $this->adminQuery(Deposit::approved())->selectRaw('DATE(created_at) as date, SUM(amount) as total')->groupBy('date')->orderBy('date')->pluck('total', 'date')->toArray();

        $this->withdrawTrend = $this->adminQuery(Withdrawal::approved())->selectRaw('DATE(created_at) as date, SUM(amount) as total')->groupBy('date')->orderBy('date')->pluck('total', 'date')->toArray();

        $this->newUsersTrend = $this->adminQuery(User::query())
            ->where('created_at', '>=', now()->subDays(30))
            ->selectRaw('DATE(created_at) as date, COUNT(*) as total')
            ->groupBy('date')
            ->orderBy('date')
            ->pluck('total', 'date')
            ->toArray();
    }

    /** ================= PENDING ACTIONS ================= */
    private function loadPendingActions(): void
    {
        $this->pendingActions = [
            'Pending KYC' => $this->adminQuery(Kyc::pending())->count(),
            'Pending Deposits' => $this->adminQuery(Deposit::pending())->count(),
            'Pending Withdrawals' => $this->adminQuery(Withdrawal::pending())->count(),
        ];
    }

    /** ================= TOP USERS ================= */
    private function loadTopUsers(): void
    {
        $this->topUsersByBalance = $this->adminQuery(User::query())
            ->withSum('accounts as total_balance', 'balance')
            ->orderByDesc('total_balance')
            ->take(10)
            ->get(['id', 'name'])
            ->map(
                fn($u) => [
                    'id' => $u->id,
                    'name' => $u->name,
                    'balance' => (float) $u->total_balance,
                ],
            );
    }

    /** ================= DEPOSITS & WITHDRAWALS ================= */
    private function loadDepositsAndWithdrawals(): void
    {
        $this->completedDeposits = $this->adminQuery(Deposit::approved())->sum('amount');
        $this->pendingDeposits = $this->adminQuery(Deposit::pending())->sum('amount');
        $this->totalWithdrawals = $this->adminQuery(Withdrawal::query())->sum('amount');
        $this->pendingWithdrawals = $this->adminQuery(Withdrawal::pending())->sum('amount');
    }

    /** ================= BALANCES ================= */
    private function loadBalances(): void
    {
        $accounts = $this->adminQuery(Account::query())->with('reserves')->get();

        $this->totalBalances = $accounts->sum('balance');
        $this->availableBalances = $accounts->sum(fn($acc) => (float) $acc->available_balance);
        $this->totalPendingReserves = $this->adminQuery(WalletReserve::pending())->sum('amount');
    }

    /** ================= KYC ================= */
    private function loadKYCStats(): void
    {
        $kycCounts = $this->adminQuery(Kyc::query())->selectRaw('status, COUNT(*) as count')->groupBy('status')->pluck('count', 'status')->toArray();

        $this->pendingKYC = $kycCounts['pending'] ?? 0;
        $this->verifiedKYC = $kycCounts['verified'] ?? 0;
        $this->rejectedKYC = $kycCounts['rejected'] ?? 0;
    }

    /** ================= REFERRALS ================= */
    private function loadReferralStats(): void
    {
        $this->totalReferralEarnings = $this->adminQuery(Transaction::query()->where('type', 'referral_bonus'))->sum('amount');
    }

    /** ================= LOAN TRENDS ================= */
    private function loadLoanTrends(): void
    {
        $startDate = now()->subDays(29)->startOfDay();
        $endDate = now()->endOfDay();

        $this->loanTrendDates = collect(range(0, 29))
            ->map(
                fn($i) => now()
                    ->subDays(29 - $i)
                    ->format('Y-m-d'),
            )
            ->toArray();

        $loanDisbursementsRaw = $this->adminQuery(Loan::query())
            ->whereNotNull('approved_at')
            ->whereBetween('approved_at', [$startDate, $endDate])
            ->selectRaw('DATE(approved_at) as date, SUM(amount) as total')
            ->groupBy('date')
            ->pluck('total', 'date')
            ->toArray();

        $loanRepaymentsRaw = $this->adminQuery(LoanInstallment::query())
            ->whereNotNull('paid_at')
            ->whereBetween('paid_at', [$startDate, $endDate])
            ->selectRaw('DATE(paid_at) as date, SUM(total) as total')
            ->groupBy('date')
            ->pluck('total', 'date')
            ->toArray();

        $overdueLoansRaw = $this->adminQuery(Loan::query())
            ->where('status', 'overdue')
            ->whereBetween('updated_at', [$startDate, $endDate])
            ->selectRaw('DATE(updated_at) as date, COUNT(*) as total')
            ->groupBy('date')
            ->pluck('total', 'date')
            ->toArray();

        $this->loanDisbursementsTrend = array_map(fn($date) => (float) ($loanDisbursementsRaw[$date] ?? 0), $this->loanTrendDates);
        $this->loanRepaymentsTrend = array_map(fn($date) => (float) ($loanRepaymentsRaw[$date] ?? 0), $this->loanTrendDates);
        $this->loanOverdueTrend = array_map(fn($date) => (int) ($overdueLoansRaw[$date] ?? 0), $this->loanTrendDates);
    }

    /** ================= RECENT TRANSACTIONS ================= */
    private function loadRecentTransactions(): void
    {
        $this->recentTransactions = $this->adminQuery(\App\Models\Transaction::query())
            ->latest()
            ->with(['account.profile.user'])
            ->take(10)
            ->get();
    }

    /** ================= DASHBOARD CARDS ================= */
    private function loadDashboardCards(): void
    {
        $this->cardStats = [
            $this->card('users', $this->totalUsers, 'Total Users'),
            $this->card('user-plus', $this->newUsers7d, 'New Users (7d)'),
            $this->card('user-circle', $this->activeUsers7d, 'Active Users (7d)'),
            $this->card('check-badge', $this->completedDeposits, 'Completed Deposits', true),
            $this->card('beaker', $this->pendingDeposits, 'Pending Deposits', true),
            $this->card('banknotes', $this->totalWithdrawals, 'Total Withdrawals', true),
            $this->card('clock', $this->pendingWithdrawals, 'Pending Withdrawals', true),
            $this->card('wallet', $this->totalBalances, 'Total Balances', true),
            $this->card('wallet', $this->availableBalances, 'Available Balances', true),
            $this->card('lock-closed', $this->totalPendingReserves, 'Total Pending Reserves', true),
            $this->card('exclamation-circle', $this->pendingKYC, 'Pending KYC'),
            $this->card('x-circle', $this->rejectedKYC, 'Rejected KYC'),
            $this->card('check-circle', $this->verifiedKYC, 'Verified KYC'),
            $this->card('gift', $this->totalReferralEarnings, 'Total Referral Earnings', true),
        ];

        $this->cardStats = array_merge($this->cardStats, $this->loanStats);
    }

    protected function card(string $icon, float|int $number, string $text, bool $currency = false): array
    {
        $colors = [['bg' => 'bg-sky-100 dark:bg-sky-900/40', 'text' => 'text-sky-600 dark:text-sky-300'], ['bg' => 'bg-emerald-100 dark:bg-emerald-900/40', 'text' => 'text-emerald-600 dark:text-emerald-300'], ['bg' => 'bg-amber-100 dark:bg-amber-900/40', 'text' => 'text-amber-600 dark:text-amber-300'], ['bg' => 'bg-rose-100 dark:bg-rose-900/40', 'text' => 'text-rose-600 dark:text-rose-300'], ['bg' => 'bg-indigo-100 dark:bg-indigo-900/40', 'text' => 'text-indigo-600 dark:text-indigo-300'], ['bg' => 'bg-violet-100 dark:bg-violet-900/40', 'text' => 'text-violet-600 dark:text-violet-300'], ['bg' => 'bg-cyan-100 dark:bg-cyan-900/40', 'text' => 'text-cyan-600 dark:text-cyan-300'], ['bg' => 'bg-blue-100 dark:bg-blue-900/40', 'text' => 'text-blue-600 dark:text-blue-300']];

        $index = crc32($text) % count($colors);

        return [
            'icon' => $icon,
            'number' => (float) $number,
            'text' => $text,
            'is_currency' => $currency,
            'icon_bg' => $colors[$index]['bg'],
            'icon_text' => $colors[$index]['text'],
        ];
    }
};
?>

<div class="py-5 space-y-6">

    <div>
        <h1 class="text-base md:text-2xl text-gray-400 dark:text-gray-100 font-bold">
            <span id="greeting"></span>,
            <?php echo e(\Illuminate\Support\Facades\Auth::guard('admin')->user()->name); ?>

            !
        </h1>
        <p class="mt-1 text-gray-400 dark:text-gray-100">Here’s your dashboard overview</p>

        <script>
            function updateGreeting() {
                const greetingEl = document.getElementById('greeting');
                if (!greetingEl)
                    return;


                const now = new Date();
                const hour = now.getHours();
                let greetingText = '';

                if (hour >= 5 && hour < 12) {
                    greetingText = 'Good morning 🌞';
                } else if (hour >= 12 && hour < 16) {
                    greetingText = 'Good afternoon 🌤';
                } else if (hour >= 16 && hour < 20) {
                    greetingText = 'Good evening 🌇';
                } else {
                    greetingText = 'Good night 🌙';
                }
                greetingEl.textContent = greetingText;
            }

            // Run on page load
            updateGreeting();

            // Run after every Livewire update
            document.addEventListener('livewire:load', () => {
                Livewire.hook('message.processed', () => {
                    updateGreeting();
                });
            });

            // Optional: refresh every minute
            setInterval(updateGreeting, 60 * 1000);
        </script>

    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 pb-4">
        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $cardStats; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $card): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?>
            <div
                class="bg-white dark:bg-gray-900
                                       border border-gray-100 dark:border-gray-800
                                       rounded-xl shadow-sm
                                       p-5 transition duration-300
                                       hover:shadow-md
                                       flex justify-between items-center">

                <div>
                    <h4
                        class="text-xs uppercase mb-2 font-medium
                                                       text-gray-500 dark:text-gray-400">
                        <?php echo e($card['text']); ?>

                    </h4>

                    <p class="text-xl font-bold text-gray-800 dark:text-white" x-data x-init="let el = $el;
                    let val = <?php echo e($card['number']); ?>;
                    let start = 0;
                    let duration = 1000;
                    let step = Math.ceil(val / (duration / 16));
                    let interval = setInterval(() => {
                        start += step;
                        if (start >= val) {
                            start = val;
                            clearInterval(interval);
                        }
                        el.textContent = <?php echo e($card['is_currency'] ? "'$' + " : ''); ?> start.toLocaleString();
                    }, 16);">
                        0
                    </p>
                </div>

                <!-- Random Colored Icon -->
                <div class="w-12 h-12 rounded-full flex items-center justify-center <?php echo e($card['icon_bg']); ?>">
                    <?php if (isset($component)) { $__componentOriginal511d4862ff04963c3c16115c05a86a9d = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal511d4862ff04963c3c16115c05a86a9d = $attributes; } ?>
<?php $component = Illuminate\View\DynamicComponent::resolve(['component' => 'flux::icon.' . $card['icon']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('dynamic-component'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\DynamicComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['class' => 'w-5 h-5 '.e($card['icon_text']).'','variant' => 'solid']); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>

<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal511d4862ff04963c3c16115c05a86a9d)): ?>
<?php $attributes = $__attributesOriginal511d4862ff04963c3c16115c05a86a9d; ?>
<?php unset($__attributesOriginal511d4862ff04963c3c16115c05a86a9d); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal511d4862ff04963c3c16115c05a86a9d)): ?>
<?php $component = $__componentOriginal511d4862ff04963c3c16115c05a86a9d; ?>
<?php unset($__componentOriginal511d4862ff04963c3c16115c05a86a9d); ?>
<?php endif; ?>
                </div>


            </div>
        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>
    </div>


    <!-- === Charts Section === -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- Deposits vs Withdrawals -->
        <div class="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-md">
            <h3 class="text-lg font-semibold mb-4">Deposits vs Withdrawals</h3>
            <div id="deposit-withdraw-chart" style="height: 300px;"></div>
        </div>

        <!-- Users by Country -->
        <div class="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-md">
            <h3 class="text-lg font-semibold mb-4">Users by Country</h3>
            <div id="users-country-chart" style="height: 300px;"></div>
        </div>

        <!-- Users by Browser -->
        <div class="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-md">
            <h3 class="text-lg font-semibold mb-4">Users by Browser</h3>
            <div id="users-browser-chart" style="height: 300px;"></div>
        </div>

        <!-- New Users Trend -->
        <div class="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-md mt-6">
            <h3 class="text-lg font-semibold mb-4">New Users Last 30 Days</h3>
            <div id="new-users-chart" style="height: 300px;"></div>
        </div>

        <!-- Pending Actions -->
        <div class="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-md mt-6">
            <h3 class="text-lg font-semibold mb-4">Pending Actions</h3>
            <div id="pending-actions-chart" style="height: 300px;"></div>
        </div>

        <!-- Top Users by Balance -->
        <div class="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-md mt-6">
            <h3 class="text-lg font-semibold mb-4">Top 10 Users by Balance</h3>
            <div id="top-users-chart" style="height: 400px;"></div>
        </div>
    </div>


    <div class="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-md mt-6">
        <h3 class="text-lg font-semibold mb-4">Loans Trends (Last 30 Days)</h3>
        <div id="loan-trends-chart" style="height: 300px;"></div>
    </div>

    <div
        class="bg-white/90 dark:bg-gray-800/90 backdrop-blur-md rounded-2xl shadow-lg dark:shadow-gray-900/50 overflow-hidden border border-white/20 dark:border-gray-700/50">

        
        <div class="px-5 py-3 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
            <div class="flex items-center gap-3">
                <div class="w-8 h-8 bg-sky-500 dark:bg-sky-600 rounded-lg flex items-center justify-center">
                    <?php if (isset($component)) { $__componentOriginalda6e47aecf1695047ea823532321ccd7 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalda6e47aecf1695047ea823532321ccd7 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'e60dd9d2c3a62d619c9acb38f20d5aa5::icon.arrows-right-left','data' => ['class' => 'w-4 h-4 text-white']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('flux::icon.arrows-right-left'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['class' => 'w-4 h-4 text-white']); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>

<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalda6e47aecf1695047ea823532321ccd7)): ?>
<?php $attributes = $__attributesOriginalda6e47aecf1695047ea823532321ccd7; ?>
<?php unset($__attributesOriginalda6e47aecf1695047ea823532321ccd7); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalda6e47aecf1695047ea823532321ccd7)): ?>
<?php $component = $__componentOriginalda6e47aecf1695047ea823532321ccd7; ?>
<?php unset($__componentOriginalda6e47aecf1695047ea823532321ccd7); ?>
<?php endif; ?>
                </div>

                <h3 class="text-sm font-semibold text-gray-900 dark:text-gray-50">
                    Recent Activity
                </h3>
            </div>

            <a href="<?php echo e(route('admin.dashboard')); ?>"
                class="text-xs font-semibold text-sky-600 hover:text-sky-700 dark:text-sky-300 dark:hover:text-sky-200 transition">
                View all
            </a>
        </div>

        <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($recentTransactions->isEmpty()): ?>
            
            <div class="py-12 text-center text-sm text-gray-500 dark:text-gray-400">
                No transactions yet
            </div>
        <?php else: ?>
            <ul class="divide-y divide-gray-100 dark:divide-gray-700">
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::openLoop(); ?><?php endif; ?><?php $__currentLoopData = $recentTransactions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $transaction): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::startLoop($loop->index); ?><?php endif; ?>
                    <?php
                        $icons = [
                            'deposit' => 'arrow-down-tray',
                            'withdrawal' => 'arrow-up-tray',
                            'transfer_in' => 'arrow-down-tray',
                            'transfer_out' => 'arrow-up-tray',
                            'trade' => 'chart-bar',
                            'referral_bonus' => 'user-plus',
                            'signup_bonus' => 'user-plus',
                        ];

                        $badgeClass = $transaction->badge_classes['bg'];
                        $iconBg = $transaction->badge_classes['icon'];

                        $actionUrl = $transaction->admin_url;
                        $userUrl = $transaction->user_url;
                    ?>

                    <li <?php if($actionUrl): ?> onclick="window.location='<?php echo e($actionUrl); ?>'" <?php endif; ?>
                        class="px-5 py-3 flex items-center justify-between
                                           hover:bg-gray-50 dark:hover:bg-gray-800/40 transition
                                           rounded-lg my-1
                                           <?php echo e($actionUrl ? 'cursor-pointer' : 'cursor-default opacity-70'); ?>">

                        
                        <div class="flex items-center gap-3 min-w-0">
                            <div
                                class="w-9 h-9 rounded-xl flex items-center justify-center <?php echo e($iconBg); ?> shrink-0">
                                <?php if (isset($component)) { $__componentOriginalc7d5f44bf2a2d803ed0b55f72f1f82e2 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalc7d5f44bf2a2d803ed0b55f72f1f82e2 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'e60dd9d2c3a62d619c9acb38f20d5aa5::icon.index','data' => ['name' => ''.e($icons[$transaction->type] ?? 'square-3-stack-3d').'','class' => 'w-4 h-4 text-white']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('flux::icon'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['name' => ''.e($icons[$transaction->type] ?? 'square-3-stack-3d').'','class' => 'w-4 h-4 text-white']); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>

<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalc7d5f44bf2a2d803ed0b55f72f1f82e2)): ?>
<?php $attributes = $__attributesOriginalc7d5f44bf2a2d803ed0b55f72f1f82e2; ?>
<?php unset($__attributesOriginalc7d5f44bf2a2d803ed0b55f72f1f82e2); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalc7d5f44bf2a2d803ed0b55f72f1f82e2)): ?>
<?php $component = $__componentOriginalc7d5f44bf2a2d803ed0b55f72f1f82e2; ?>
<?php unset($__componentOriginalc7d5f44bf2a2d803ed0b55f72f1f82e2); ?>
<?php endif; ?>
                            </div>

                            <div class="flex flex-col min-w-0">
                                <p class="text-sm font-medium text-gray-700 dark:text-gray-200 capitalize truncate">
                                    <?php echo e(str_replace('_', ' ', $transaction->type)); ?>

                                </p>
                                <p class="text-xs text-gray-400 dark:text-gray-500 truncate">
                                    <?php echo e($transaction->created_at->diffForHumans()); ?>

                                    <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($userUrl): ?>
                                        •
                                        <?php echo e($transaction->account?->profile?->user?->name); ?>

                                    <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                                </p>
                            </div>
                        </div>

                        
                        <div class="text-right flex flex-col items-end gap-2 shrink-0">
                            <p class="text-sm font-semibold text-gray-900 dark:text-white">
                                <?php echo e($transaction->formatted_amount); ?>

                            </p>

                            <span
                                class="px-2 py-0.5 text-xs font-medium rounded-full <?php echo e($badgeClass); ?>"><?php echo e(ucfirst($transaction->status)); ?>

                            </span>

                            <div class="flex flex-col sm:flex-row items-center text-center gap-1">
                                
                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($actionUrl): ?>
                                    <a onclick="event.stopPropagation()" href="<?php echo e($actionUrl); ?>"
                                        class="inline-flex items-center gap-1 text-xs font-semibold
                                                                          px-3 py-1 rounded-full
                                                                          bg-sky-50 text-sky-700 hover:bg-sky-100
                                                                          dark:bg-sky-900/30 dark:text-sky-300 dark:hover:bg-sky-900/50
                                                                          ring-1 ring-sky-200 dark:ring-sky-700 transition">
                                        View
                                        <?php if (isset($component)) { $__componentOriginal907d253d71b32d64c487f317dab7cfd3 = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginal907d253d71b32d64c487f317dab7cfd3 = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'e60dd9d2c3a62d619c9acb38f20d5aa5::icon.arrow-top-right-on-square','data' => ['class' => 'w-3.5 h-3.5']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('flux::icon.arrow-top-right-on-square'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['class' => 'w-3.5 h-3.5']); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>

<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginal907d253d71b32d64c487f317dab7cfd3)): ?>
<?php $attributes = $__attributesOriginal907d253d71b32d64c487f317dab7cfd3; ?>
<?php unset($__attributesOriginal907d253d71b32d64c487f317dab7cfd3); ?>
<?php endif; ?>
<?php if (isset($__componentOriginal907d253d71b32d64c487f317dab7cfd3)): ?>
<?php $component = $__componentOriginal907d253d71b32d64c487f317dab7cfd3; ?>
<?php unset($__componentOriginal907d253d71b32d64c487f317dab7cfd3); ?>
<?php endif; ?>
                                    </a>
                                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>

                                
                                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if BLOCK]><![endif]--><?php endif; ?><?php if($userUrl): ?>
                                    <a onclick="event.stopPropagation()" href="<?php echo e($userUrl); ?>"
                                        class="inline-flex items-center gap-1 text-xs font-semibold
                                                                          px-3 py-1 rounded-full
                                                                          bg-gray-50 text-gray-700 hover:bg-gray-100
                                                                          dark:bg-gray-900/30 dark:text-gray-300 dark:hover:bg-gray-900/50
                                                                          ring-1 ring-gray-200 dark:ring-gray-700 transition">
                                        View User
                                        <?php if (isset($component)) { $__componentOriginalcbe89caa4ae8c58f7efd0ed6343c35ff = $component; } ?>
<?php if (isset($attributes)) { $__attributesOriginalcbe89caa4ae8c58f7efd0ed6343c35ff = $attributes; } ?>
<?php $component = Illuminate\View\AnonymousComponent::resolve(['view' => 'e60dd9d2c3a62d619c9acb38f20d5aa5::icon.user','data' => ['class' => 'w-3.5 h-3.5']] + (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag ? $attributes->all() : [])); ?>
<?php $component->withName('flux::icon.user'); ?>
<?php if ($component->shouldRender()): ?>
<?php $__env->startComponent($component->resolveView(), $component->data()); ?>
<?php if (isset($attributes) && $attributes instanceof Illuminate\View\ComponentAttributeBag): ?>
<?php $attributes = $attributes->except(\Illuminate\View\AnonymousComponent::ignoredParameterNames()); ?>
<?php endif; ?>
<?php $component->withAttributes(['class' => 'w-3.5 h-3.5']); ?>
<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey($component); ?>

<?php echo $__env->renderComponent(); ?>
<?php endif; ?>
<?php if (isset($__attributesOriginalcbe89caa4ae8c58f7efd0ed6343c35ff)): ?>
<?php $attributes = $__attributesOriginalcbe89caa4ae8c58f7efd0ed6343c35ff; ?>
<?php unset($__attributesOriginalcbe89caa4ae8c58f7efd0ed6343c35ff); ?>
<?php endif; ?>
<?php if (isset($__componentOriginalcbe89caa4ae8c58f7efd0ed6343c35ff)): ?>
<?php $component = $__componentOriginalcbe89caa4ae8c58f7efd0ed6343c35ff; ?>
<?php unset($__componentOriginalcbe89caa4ae8c58f7efd0ed6343c35ff); ?>
<?php endif; ?>
                                    </a>
                                <?php else: ?>
                                    <span class="text-xs text-gray-400">No user</span>
                                <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
                            </div>
                        </div>
                    </li>
                <?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::endLoop(); ?><?php endif; ?><?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::closeLoop(); ?><?php endif; ?>

            </ul>

        <?php endif; ?><?php if(\Livewire\Mechanisms\ExtendBlade\ExtendBlade::isRenderingLivewireComponent()): ?><!--[if ENDBLOCK]><![endif]--><?php endif; ?>
    </div>


    <!-- === Chart Data Holder === -->
    <div id="charts-data" data-deposit='<?php echo json_encode($depositTrend ?: [], 15, 512) ?>' data-withdraw='<?php echo json_encode($withdrawTrend ?: [], 15, 512) ?>'
        data-dates='<?php echo json_encode(array_keys($depositTrend) ?: [], 15, 512) ?>' data-users-by-browser='<?php echo json_encode($usersByBrowser ?: [], 15, 512) ?>'
        data-users-by-country='<?php echo json_encode($usersByCountry ?: [], 15, 512) ?>' data-new-users='<?php echo json_encode($newUsersTrend ?: [], 15, 512) ?>'
        data-pending-actions='<?php echo json_encode($pendingActions ?: [], 15, 512) ?>' data-top-users='<?php echo json_encode($topUsersByBalance ?: [], 15, 512) ?>'
        data-loan-approval='<?php echo json_encode($loanDisbursementsTrend, 15, 512) ?>' data-loan-repayment='<?php echo json_encode($loanRepaymentsTrend, 15, 512) ?>'
        data-loan-overdue='<?php echo json_encode($loanOverdueTrend, 15, 512) ?>' data-loan-dates='<?php echo json_encode($loanTrendDates, 15, 512) ?>'>
    </div>


    <script>
        const chartsEl = document.getElementById('charts-data');

        // ====================== Deposits / Withdrawals ======================
        const depositObj = JSON.parse(chartsEl.dataset.deposit);
        const depositTrend = Object.values(depositObj).map(Number);
        const depositDates = Object.keys(depositObj);

        const withdrawObj = JSON.parse(chartsEl.dataset.withdraw);
        const withdrawTrend = Object.values(withdrawObj).map(Number);

        const depositWithdrawChart = echarts.init(document.getElementById('deposit-withdraw-chart'));
        depositWithdrawChart.setOption({
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['Deposits', 'Withdrawals']
            },
            xAxis: {
                type: 'category',
                data: depositDates
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                name: 'Deposits',
                type: 'line',
                data: depositTrend
            }, {
                name: 'Withdrawals',
                type: 'line',
                data: withdrawTrend
            }]
        });

        // ====================== Users by Browser ======================
        const usersByBrowserRaw = JSON.parse(chartsEl.dataset.usersByBrowser);
        const usersByBrowserLabels = usersByBrowserRaw.map(u => u.browser || 'Unknown');
        const usersByBrowserData = usersByBrowserRaw.map(u => Number(u.count));

        const usersBrowserChart = echarts.init(document.getElementById('users-browser-chart'));
        usersBrowserChart.setOption({
            tooltip: {
                trigger: 'item'
            },
            legend: {
                top: '5%',
                left: 'center'
            },
            series: [{
                name: 'Users by Browser',
                type: 'pie',
                radius: [
                    '40%', '70%'
                ],
                data: usersByBrowserLabels.map(
                    (label, i) => ({
                        value: usersByBrowserData[i],
                        name: label
                    })
                ),
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0,0,0,0.5)'
                    }
                }
            }]
        });

        // ====================== Users by Country ======================
        const usersByCountryRaw = JSON.parse(chartsEl.dataset.usersByCountry);
        const usersByCountryLabels = usersByCountryRaw.map(u => u.location || 'Unknown');
        const usersByCountryData = usersByCountryRaw.map(u => Number(u.count));

        const usersCountryChart = echarts.init(document.getElementById('users-country-chart'));
        usersCountryChart.setOption({
            tooltip: {
                trigger: 'item'
            },
            legend: {
                top: '5%',
                left: 'center'
            },
            series: [{
                name: 'Users by Country',
                type: 'pie',
                radius: [
                    '40%', '70%'
                ],
                data: usersByCountryLabels.map(
                    (label, i) => ({
                        value: usersByCountryData[i],
                        name: label
                    })
                ),
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0,0,0,0.5)'
                    }
                }
            }]
        });

        // ====================== New Users Last 30 Days ======================
        const newUsersObj = JSON.parse(chartsEl.dataset.newUsers);
        const newUsersDates = Object.keys(newUsersObj);
        const newUsersData = Object.values(newUsersObj);

        const newUsersChart = echarts.init(document.getElementById('new-users-chart'));
        newUsersChart.setOption({
            tooltip: {
                trigger: 'axis'
            },
            xAxis: {
                type: 'category',
                data: newUsersDates
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                name: 'New Users',
                type: 'line',
                data: newUsersData,
                smooth: true
            }]
        });

        // ====================== Pending Actions ======================
        const pendingActionsObj = JSON.parse(chartsEl.dataset.pendingActions);
        const pendingLabels = Object.keys(pendingActionsObj);
        const pendingData = Object.values(pendingActionsObj);

        const pendingChart = echarts.init(document.getElementById('pending-actions-chart'));
        pendingChart.setOption({
            tooltip: {
                trigger: 'item'
            },
            legend: {
                top: '5%',
                left: 'center'
            },
            series: [{
                name: 'Pending Actions',
                type: 'pie',
                radius: [
                    '40%', '70%'
                ],
                data: pendingLabels.map(
                    (label, i) => ({
                        value: pendingData[i],
                        name: label
                    })
                ),
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0,0,0,0.5)'
                    }
                }
            }]
        });

        // ====================== Top Users by Balance ======================
        const topUsersRaw = JSON.parse(chartsEl.dataset.topUsers);
        const topUsersLabels = topUsersRaw.map(u => u.name);
        const topUsersData = topUsersRaw.map(u => Number(u.balance));

        const topUsersChart = echarts.init(document.getElementById('top-users-chart'));
        topUsersChart.setOption({
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            xAxis: {
                type: 'value'
            },
            yAxis: {
                type: 'category',
                data: topUsersLabels,
                inverse: true
            },
            series: [{
                name: 'Balance',
                type: 'bar',
                data: topUsersData,
                itemStyle: {
                    color: '#4f46e5'
                }
            }]
        });

        // ====================== Loans TRENDS ======================
        const loanDates = JSON.parse(chartsEl.dataset.loanDates); // all dates, even if no data
        const loanApprovalRaw = JSON.parse(chartsEl.dataset.loanApproval);
        const loanRepaymentRaw = JSON.parse(chartsEl.dataset.loanRepayment);
        const loanOverdueRaw = JSON.parse(chartsEl.dataset.loanOverdue);

        // Helper: ensure numeric values and fill missing dates with 0
        const loanApproval = loanApprovalRaw.map(Number);
        const loanRepayment = loanRepaymentRaw.map(Number);
        const loanOverdue = loanOverdueRaw.map(Number);


        const loanChart = echarts.init(document.getElementById('loan-trends-chart'));
        loanChart.setOption({
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data: ['Loan Disbursements', 'Repayments', 'Overdue Loans']
            },
            xAxis: {
                type: 'category',
                data: loanDates
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                    name: 'Loan Disbursements',
                    type: 'line',
                    smooth: true,
                    data: loanApproval
                },
                {
                    name: 'Repayments',
                    type: 'line',
                    smooth: true,
                    data: loanRepayment
                },
                {
                    name: 'Overdue Loans',
                    type: 'line',
                    smooth: true,
                    data: loanOverdue
                }
            ]
        });



        // ====================== Resize Charts on Window Resize ======================
        window.addEventListener('resize', () => {
            [
                depositWithdrawChart,
                usersBrowserChart,
                usersCountryChart,
                newUsersChart,
                pendingChart,
                topUsersChart
            ].forEach(chart => chart.resize());
        });
    </script>


</div>
<?php /**PATH /Users/macuser/Herd/Novabank/resources/views/pages/admin/⚡dashboard.blade.php ENDPATH**/ ?>