@extends('nexus.layouts.app')

@section('page-title', 'Bot Governance')
@section('sys-mode', 'BOT GOVERNANCE')

@section('head')
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js"></script>
@endsection

@section('content')

    @php
        $totals = $botOverview['totals'] ?? [];
        $plans = $botOverview['plans'] ?? [];
        $alerts = $botAlerts ?? [];
        $stl = $settlement ?? [];
        $charts = $chartData ?? [];
        $engineStatus = \App\Nexus\Engine\NexusConfig::get('nexus_status', 'inactive');
        $isActive = $engineStatus === 'active';
        $isCurrent = ($stl['is_current'] ?? true);

        $dateStart = $dates['start'] ?? now()->startOfMonth()->toDateString();
        $dateEnd = $dates['end'] ?? now()->toDateString();
        $isCurrentMonth = \Carbon\Carbon::parse($dateStart)->month === now()->month
                       && \Carbon\Carbon::parse($dateStart)->year === now()->year
                       && \Carbon\Carbon::parse($dateStart)->day === 1;
        $periodLabel = \Carbon\Carbon::parse($dateStart)->format('F Y');
        $currentMonth = request()->input('month', now()->format('Y-m'));
    @endphp

    {{-- PAGE HEADER --}}
    <div class="page-header">
        <div>
            <h1>BOT <em>GOVERNANCE</em></h1>
            <p class="page-header-sub">AI bot profit governance and performance tracking</p>
        </div>
        <div class="page-header-right">
            <span class="chip {{ $isActive ? 'chip-live' : 'chip-pending' }}">
                {{ $isActive ? 'GOVERNANCE ACTIVE' : 'GOVERNANCE STANDBY' }}
            </span>

            {{-- MONTH SELECTOR --}}
            <div class="date-controls" style="margin-top: 8px;">
                <div class="month-selector" id="botMonthSelector">
                    <button type="button" class="month-selector-btn" id="botMonthSelectorBtn">
                        {{ $periodLabel }}
                    </button>
                    <div class="month-selector-dropdown" id="botMonthSelectorDropdown">
                        @foreach ($availableMonths ?? [] as $m)
                            <div class="month-option {{ $currentMonth === $m ? 'active' : '' }}"
                                 data-month="{{ $m }}">
                                {{ \Carbon\Carbon::parse($m . '-01')->format('F Y') }}
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>
        </div>
    </div>

    @if (!$isActive)
        <div class="bot-standby-notice">
            <span class="bot-standby-icon">!</span>
            <span class="bot-standby-text">NEXUS is inactive. Governance data is calculated but not applied. Trade ranges and success rates below reflect what governance WOULD do.</span>
        </div>
    @endif


    {{-- ALERTS (current month only) --}}

    @if ($isCurrent && count($alerts) > 0)
        <div class="section-header">
            <span class="section-label">Alerts</span>
            <span class="section-right">{{ count($alerts) }} item(s) require attention</span>
        </div>

        @foreach ($alerts as $alert)
            <div class="alert-row {{ $alert['level'] === 'critical' ? 'critical' : '' }}">
                <span class="alert-prefix">{{ $alert['level'] === 'critical' ? 'CRIT' : ($alert['level'] === 'warning' ? 'WARN' : 'INFO') }}</span>
                <span class="alert-text">{{ $alert['message'] }}</span>
            </div>
        @endforeach
    @endif


    {{-- STAT STRIP --}}

    <div class="stat-strip">
        <div class="stat-cell">
            <div class="stat-label">{{ $isCurrent ? 'Active Bots' : 'Bots (Period)' }}</div>
            <div class="stat-value orange">{{ $totals['bots'] ?? 0 }}</div>
        </div>
        <div class="stat-cell">
            <div class="stat-label">Capital {{ $isCurrent ? 'Under Management' : '(Period)' }}</div>
            <div class="stat-value">${{ number_format($totals['capital'] ?? 0, 2) }}</div>
        </div>
        <div class="stat-cell">
            <div class="stat-label">Total Profit</div>
            <div class="stat-value text-green">${{ number_format($totals['profit'] ?? 0, 2) }}</div>
        </div>
        <div class="stat-cell">
            <div class="stat-label">Track Status</div>
            <div class="stat-value">
                <span class="text-green">{{ $totals['on_track'] ?? 0 }}</span>
                <span class="text-dim">/</span>
                <span class="text-yellow">{{ $totals['hot'] ?? 0 }}</span>
                <span class="text-dim">/</span>
                <span class="text-red">{{ $totals['cold'] ?? 0 }}</span>
                @if (($totals['settled'] ?? 0) > 0)
                    <span class="text-dim">/</span>
                    <span class="text-dim">{{ $totals['settled'] }}</span>
                @endif
            </div>
            <div class="stat-sub">On Track / Hot / Cold{{ ($totals['settled'] ?? 0) > 0 ? ' / Settled' : '' }}</div>
        </div>
    </div>


    {{-- CHARTS ROW --}}

    <div class="chart-row">
        <div class="chart-panel">
            <div class="chart-title">Capital Distribution</div>
            <div class="chart-wrap h250" style="position: relative;">
                <canvas id="capitalChart"></canvas>
                @php $totalCap = $charts['total_capital'] ?? 0; @endphp
                @if ($totalCap > 0)
                    <div class="chart-center-label">
                        <div class="chart-center-value">${{ $totalCap >= 1000000 ? number_format($totalCap / 1000000, 1) . 'M' : number_format($totalCap / 1000, 0) . 'K' }}</div>
                        <div class="chart-center-text">TOTAL</div>
                    </div>
                @endif
            </div>
        </div>
        <div class="chart-panel">
            <div class="chart-title">Profit vs Target <span class="text-dim">by plan</span></div>
            <div class="chart-wrap h250">
                <canvas id="profitTargetChart"></canvas>
            </div>
        </div>
        <div class="chart-panel">
            <div class="chart-title">Track Status</div>
            <div class="chart-wrap h250" style="position: relative;">
                <canvas id="trackChart"></canvas>
                <div class="chart-center-label">
                    <div class="chart-center-value">{{ $totals['bots'] ?? 0 }}</div>
                    <div class="chart-center-text">BOTS</div>
                </div>
            </div>
        </div>
    </div>


    {{-- SETTLEMENT PIPELINE --}}

    <div class="section-header" style="flex-wrap: wrap; gap: 8px;">
        <span class="section-label">Settlement {{ $isCurrent ? 'Pipeline' : 'Results' }}</span>
        <div style="display: flex; align-items: center; gap: 16px;">
            <span class="section-right" style="margin: 0;">
                @if ($isCurrent)
                    {{ $stl['expiring_count'] ?? 0 }} expiring this week
                    @if (($stl['expiring_at_risk'] ?? 0) > 0)
                        &bull; <span class="text-red">{{ $stl['expiring_at_risk'] }} at risk</span>
                    @endif
                    &bull;
                @endif
                {{ $stl['settled_count'] ?? 0 }} settled{{ $isCurrent ? ' this month' : '' }}
                @if (($stl['settled_count'] ?? 0) > 0)
                    &bull; {{ $stl['settlement_accuracy'] ?? 0 }}% in range
                @endif
            </span>
        </div>
    </div>

    {{-- Expiring soon (current only) --}}
    @if ($isCurrent)
        @php $expiring = $stl['expiring_soon'] ?? []; @endphp
        @if (count($expiring) > 0)
            <div class="data-table-wrap">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Bot</th><th>User</th><th>Plan</th>
                            <th class="col-right">Capital</th><th class="col-right">Profit %</th>
                            <th class="col-right">Target %</th><th class="col-right">Days Left</th><th>Risk</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($expiring as $ex)
                            <tr>
                                <td>#{{ $ex['bot_id'] }}</td>
                                <td>{{ $ex['username'] }}</td>
                                <td>{{ $ex['plan'] }}</td>
                                <td class="col-right">${{ number_format($ex['capital'], 2) }}</td>
                                <td class="col-right {{ $ex['at_risk'] ? 'text-red' : 'text-green' }}">{{ number_format($ex['profit_pct'], 2) }}%</td>
                                <td class="col-right text-dim">{{ number_format($ex['target_pct'], 2) }}%</td>
                                <td class="col-right">{{ $ex['days_left'] }}d</td>
                                <td>
                                    @if ($ex['at_risk'])
                                        <span class="chip chip-sm chip-error">AT RISK</span>
                                    @elseif ($ex['has_f_pfit'])
                                        <span class="chip chip-sm chip-active">F_PFIT</span>
                                    @else
                                        <span class="chip chip-sm chip-completed">ON TRACK</span>
                                    @endif
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        @else
            <div class="empty-state"><span class="empty-state-text">No bots expiring within 7 days</span></div>
        @endif
    @endif

    {{-- Settled bots --}}
    @php $settled = $stl['settled'] ?? []; @endphp
    @if (count($settled) > 0)
        @if ($isCurrent)
            <div class="section-header">
                <span class="section-label">Settled This Month</span>
                <span class="section-right">{{ $stl['in_range_count'] ?? 0 }}/{{ $stl['settled_count'] ?? 0 }} in range ({{ $stl['settlement_accuracy'] ?? 0 }}%)</span>
            </div>
        @endif

        <div class="data-table-wrap">
            {{-- Settled table controls --}}
            <div class="table-controls" style="padding: 10px 14px; border-bottom: 1px solid var(--line); display: flex; align-items: center; justify-content: space-between;">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <span class="stat-label" style="margin: 0;">Showing</span>
                    <select id="settledPerPage" class="filter-select" style="width: auto; min-width: 60px; padding: 4px 8px; font-size: 11px;">
                        <option value="20" selected>20</option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                        <option value="all">All</option>
                    </select>
                    <span class="stat-label" style="margin: 0;">of <em id="settledTotalCount">{{ count($settled) }}</em></span>
                </div>
            </div>
            <table class="data-table" id="settledTable">
                <thead>
                    <tr>
                        <th>Bot</th><th>User</th><th>Plan</th>
                        <th class="col-right">Capital</th><th class="col-right">Profit %</th>
                        <th class="col-right">Target Range</th><th>Result</th>
                    </tr>
                </thead>
                <tbody id="settledTableBody">
                    @foreach ($settled as $st)
                        <tr>
                            <td>#{{ $st['bot_id'] }}</td>
                            <td>{{ $st['username'] }}</td>
                            <td>{{ $st['plan'] }}</td>
                            <td class="col-right">${{ number_format($st['capital'], 2) }}</td>
                            <td class="col-right {{ $st['in_range'] ? 'text-green' : 'text-red' }}">{{ number_format($st['profit_pct'], 2) }}%</td>
                            <td class="col-right text-dim">{{ $st['target_min'] }}% - {{ $st['target_max'] }}%</td>
                            <td>
                                @if ($st['in_range'])
                                    <span class="chip chip-sm chip-completed">IN RANGE</span>
                                @elseif ($st['used_f_pfit'])
                                    <span class="chip chip-sm chip-active">F_PFIT</span>
                                @else
                                    <span class="chip chip-sm chip-error">OUT OF RANGE</span>
                                @endif
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
            {{-- Settled pagination --}}
            <div class="ajax-pagination" id="settledPagination" style="display: none;">
                <button type="button" class="ajax-pagination-btn" id="settledPrev">PREV</button>
                <span class="ajax-pagination-info">Page <em id="settledCurrentPage">1</em> of <em id="settledTotalPages">1</em></span>
                <button type="button" class="ajax-pagination-btn" id="settledNext">NEXT</button>
            </div>
        </div>
    @elseif (!$isCurrent)
        <div class="empty-state"><span class="empty-state-text">No bots settled during this period</span></div>
    @endif


    {{-- PER-PLAN SECTIONS WITH AJAX TABLES --}}

    @foreach ($plans as $plan)
        @php
            $planId = $plan['plan_id'] ?? 0;
            $botCount = $plan['bot_count'] ?? 0;
            $planCapital = $plan['total_capital'] ?? 0;
            $planProfit = $plan['total_profit'] ?? 0;
            $avgProfitPct = $plan['avg_profit_pct'] ?? 0;
            $monthlyMin = $plan['nexus_monthly_min'] ?? 0;
            $monthlyMax = $plan['nexus_monthly_max'] ?? 0;
            $onTrack = $plan['on_track'] ?? 0;
            $hot = $plan['hot'] ?? 0;
            $cold = $plan['cold'] ?? 0;
        @endphp

        <div class="section-header" style="flex-wrap: wrap; gap: 8px;">
            <span class="section-label">{{ $plan['plan_name'] ?? 'Unknown Plan' }}</span>
            <div style="display: flex; align-items: center; gap: 16px;">
                <span class="section-right" style="margin: 0;">{{ $botCount }} bots &bull; ${{ number_format($planCapital, 0) }} capital &bull; Target: {{ $monthlyMin }}% - {{ $monthlyMax }}% monthly</span>
                <a href="/nexus/api/bots/export?plan_id={{ $planId }}&start={{ $dateStart }}&end={{ $dateEnd }}" class="btn-export">EXPORT CSV</a>
            </div>
        </div>

        <div class="bot-plan-summary">
            <div class="bot-plan-stat">
                <span class="stat-label">Avg Profit</span>
                <span class="bot-plan-value {{ $avgProfitPct >= $monthlyMin ? 'text-green' : ($avgProfitPct >= $monthlyMin * 0.5 ? 'text-yellow' : 'text-red') }}">{{ number_format($avgProfitPct, 2) }}%</span>
            </div>
            <div class="bot-plan-stat">
                <span class="stat-label">On Track</span>
                <span class="bot-plan-value text-green">{{ $onTrack }}</span>
            </div>
            <div class="bot-plan-stat">
                <span class="stat-label">Hot</span>
                <span class="bot-plan-value text-yellow">{{ $hot }}</span>
            </div>
            <div class="bot-plan-stat">
                <span class="stat-label">Cold</span>
                <span class="bot-plan-value text-red">{{ $cold }}</span>
            </div>
            <div class="bot-plan-stat">
                <span class="stat-label">Total Profit</span>
                <span class="bot-plan-value">${{ number_format($planProfit, 2) }}</span>
            </div>
        </div>

        {{-- AJAX Table Container --}}
        <div class="bot-table-container" id="bot-table-{{ $planId }}" data-plan-id="{{ $planId }}">

            {{-- Controls row --}}
            <div class="bot-table-controls">
                <div class="bot-table-search">
                    <input type="text" class="filter-input bot-search-input" id="bot-search-{{ $planId }}"
                           placeholder="Search username or bot ID..." data-plan="{{ $planId }}">
                </div>
                <div class="bot-table-options">
                    <span class="text-dim bot-table-info" id="bot-info-{{ $planId }}">Loading...</span>
                    <select class="filter-select bot-limit-select" id="bot-limit-{{ $planId }}" data-plan="{{ $planId }}">
                        <option value="10">10</option>
                        <option value="20" selected>20</option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                    </select>
                </div>
            </div>

            {{-- Table --}}
            <div class="data-table-wrap">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th class="bot-ajax-sort" data-sort="bot_id" data-plan="{{ $planId }}">Bot</th>
                            <th class="bot-ajax-sort" data-sort="username" data-plan="{{ $planId }}">User</th>
                            <th class="bot-ajax-sort col-right" data-sort="capital" data-plan="{{ $planId }}">Capital</th>
                            <th class="bot-ajax-sort col-right" data-sort="current_profit" data-plan="{{ $planId }}">Profit</th>
                            <th class="bot-ajax-sort col-right" data-sort="profit_pct" data-plan="{{ $planId }}">Profit %</th>
                            <th class="col-right">Target</th>
                            <th class="bot-ajax-sort col-right" data-sort="profit_of_target" data-plan="{{ $planId }}">vs Target</th>
                            <th class="bot-ajax-sort" data-sort="track_status" data-plan="{{ $planId }}">Status</th>
                            <th class="bot-ajax-sort col-right" data-sort="drift" data-plan="{{ $planId }}">Drift</th>
                            <th class="bot-ajax-sort col-right" data-sort="days_remaining" data-plan="{{ $planId }}">Days Left</th>
                            <th class="col-right hide-mobile">Base Success</th>
                        </tr>
                    </thead>
                    <tbody id="bot-tbody-{{ $planId }}">
                        <tr><td colspan="11" style="text-align: center; padding: 20px;">
                            <span class="ajax-loading-spinner">Loading <span class="loading-dot"></span></span>
                        </td></tr>
                    </tbody>
                </table>
            </div>

            {{-- Pagination --}}
            <div class="bot-table-pagination" id="bot-pagination-{{ $planId }}"></div>
        </div>

    @endforeach

    @if (empty($plans))
        <div class="empty-state" style="margin-top: 40px;">
            <span class="empty-state-text">No bot data for this period</span>
        </div>
    @endif

@endsection


@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {

    Chart.defaults.color = '#7a7a7a';
    Chart.defaults.borderColor = '#222222';
    Chart.defaults.font.family = "'IBM Plex Mono', monospace";
    Chart.defaults.font.size = 10;

    var chartColors = ['#e8842a', '#00aa00', '#ccaa00', '#cc0000', '#999999'];
    var currentStart = '{{ $dateStart }}';
    var currentEnd = '{{ $dateEnd }}';


    /* ── Capital Distribution Doughnut ── */
    var capCtx = document.getElementById('capitalChart');
    if (capCtx) {
        var capData = @json($charts['capital_by_plan'] ?? []);
        new Chart(capCtx, {
            type: 'doughnut',
            data: {
                labels: Object.keys(capData),
                datasets: [{ data: Object.values(capData), backgroundColor: chartColors.slice(0, Object.keys(capData).length), borderColor: '#0a0a0a', borderWidth: 2 }]
            },
            options: {
                responsive: true, maintainAspectRatio: false, cutout: '68%',
                plugins: {
                    legend: { position: 'bottom', labels: { padding: 12, usePointStyle: true, pointStyle: 'rect', font: { size: 9 } } },
                    tooltip: { backgroundColor: '#141414', borderColor: '#222222', borderWidth: 1, cornerRadius: 4,
                        callbacks: { label: function(ctx) { return ctx.label + ': $' + ctx.parsed.toLocaleString(); } } }
                }
            }
        });
    }

    /* ── Profit vs Target Bar Chart ── */
    var ptCtx = document.getElementById('profitTargetChart');
    if (ptCtx) {
        var ptData = @json($charts['profit_vs_target'] ?? []);
        var ptLabels = ptData.map(function(d) { return d.plan.replace(' AI', '').replace(' quick view', ''); });
        var ptActual = ptData.map(function(d) { return d.avg_profit; });
        var ptTargetMin = ptData.map(function(d) { return d.target_min; });
        var ptTargetMax = ptData.map(function(d) { return d.target_max; });

        new Chart(ptCtx, {
            type: 'bar',
            data: {
                labels: ptLabels,
                datasets: [
                    { label: 'Current Avg %', data: ptActual, backgroundColor: ptActual.map(function(v, i) { return v >= ptTargetMin[i] ? '#00aa00' : (v >= ptTargetMin[i] * 0.5 ? '#ccaa00' : '#cc0000'); }), borderRadius: 3, barPercentage: 0.5 },
                    { label: 'Target Min %', data: ptTargetMin, backgroundColor: 'rgba(232,132,42,0.15)', borderColor: 'rgba(232,132,42,0.4)', borderWidth: 1, borderRadius: 3, barPercentage: 0.5 },
                    { label: 'Target Max %', data: ptTargetMax, backgroundColor: 'rgba(232,132,42,0.08)', borderColor: 'rgba(232,132,42,0.2)', borderWidth: 1, borderRadius: 3, barPercentage: 0.5 }
                ]
            },
            options: {
                responsive: true, maintainAspectRatio: false,
                plugins: { legend: { position: 'bottom', labels: { padding: 12, usePointStyle: true, pointStyle: 'rect', font: { size: 9 } } },
                    tooltip: { backgroundColor: '#141414', borderColor: '#222222', borderWidth: 1, cornerRadius: 4, bodyFont: { size: 10 } } },
                scales: { x: { grid: { display: false }, ticks: { font: { size: 9 } } },
                    y: { grid: { color: '#222222', drawBorder: false }, ticks: { font: { size: 9 }, callback: function(v) { return v + '%'; } } } }
            }
        });
    }

    /* ── Track Status Doughnut ── */
    var trCtx = document.getElementById('trackChart');
    if (trCtx) {
        var trData = @json($charts['track_counts'] ?? []);
        var trLabels = ['On Track', 'Hot', 'Cold'];
        var trValues = [trData.ON_TRACK || 0, trData.HOT || 0, trData.COLD || 0];
        var trColors = ['#00aa00', '#ccaa00', '#cc0000'];
        if (trData.SETTLED && trData.SETTLED > 0) {
            trLabels.push('Settled');
            trValues.push(trData.SETTLED);
            trColors.push('#999999');
        }
        new Chart(trCtx, {
            type: 'doughnut',
            data: { labels: trLabels, datasets: [{ data: trValues, backgroundColor: trColors, borderColor: '#0a0a0a', borderWidth: 2 }] },
            options: { responsive: true, maintainAspectRatio: false, cutout: '68%',
                plugins: { legend: { position: 'bottom', labels: { padding: 12, usePointStyle: true, pointStyle: 'rect', font: { size: 9 } } },
                    tooltip: { backgroundColor: '#141414', borderColor: '#222222', borderWidth: 1, cornerRadius: 4, bodyFont: { size: 10 } } } }
        });
    }


    /* ── Month selector ── */
    nexus.initMonthSelector('botMonthSelector', '/nexus/bots');


    /* ── AJAX Bot Tables ── */

    var botTableState = {};

    function loadBotTable(planId) {
        var state = botTableState[planId] || { page: 1, limit: 20, sort: 'capital', dir: 'desc', search: '' };
        botTableState[planId] = state;

        var params = 'plan_id=' + planId
            + '&page=' + state.page
            + '&limit=' + state.limit
            + '&sort=' + state.sort
            + '&dir=' + state.dir
            + '&start=' + currentStart
            + '&end=' + currentEnd;
        if (state.search) params += '&search=' + encodeURIComponent(state.search);

        var tbody = document.getElementById('bot-tbody-' + planId);
        var info = document.getElementById('bot-info-' + planId);
        var pagination = document.getElementById('bot-pagination-' + planId);

        nexus.fetchJson('/nexus/api/bots/table?' + params, function (response) {
            var data = response.data || {};
            var rows = data.data || [];
            var total = data.total || 0;
            var pages = data.pages || 1;
            var page = data.page || 1;

            // Info text
            if (info) {
                var from = total > 0 ? ((page - 1) * state.limit + 1) : 0;
                var to = Math.min(page * state.limit, total);
                info.textContent = from + '-' + to + ' of ' + total;
            }

            // Render rows
            if (rows.length === 0) {
                tbody.innerHTML = '<tr><td colspan="11" style="text-align:center;padding:20px;"><span class="empty-state-text">No bots found</span></td></tr>';
            } else {
                var html = '';
                for (var i = 0; i < rows.length; i++) {
                    var b = rows[i];
                    var statusClass = b.track_status === 'ON_TRACK' ? 'chip-completed'
                        : b.track_status === 'HOT' ? 'chip-active'
                        : b.track_status === 'SETTLED' ? 'chip-pending'
                        : b.track_status === 'OUT_OF_RANGE' ? 'chip-error'
                        : 'chip-error';
                    var targetBarColor = b.profit_of_target >= 80 ? 'green' : (b.profit_of_target >= 50 ? 'yellow' : 'red');
                    var fpfitMark = b.has_f_pfit ? ' <span class="text-yellow" title="f_pfit: $' + b.f_pfit.toFixed(2) + '">*</span>' : '';

                    html += '<tr>'
                        + '<td>#' + b.bot_id + fpfitMark + '</td>'
                        + '<td><span class="user-link" onclick="nexus.showAuditTrail(' + b.user_id + ', \'' + nexusEscapeHtml(b.username) + '\')">' + nexusEscapeHtml(b.username) + '</span></td>'
                        + '<td class="col-right">$' + numberFmt(b.capital) + '</td>'
                        + '<td class="col-right ' + (b.current_profit > 0 ? 'text-green' : '') + '">$' + numberFmt(b.current_profit) + '</td>'
                        + '<td class="col-right">' + b.profit_pct.toFixed(2) + '%</td>'
                        + '<td class="col-right text-dim">' + b.target_pct.toFixed(1) + '%</td>'
                        + '<td class="col-right"><div class="inline-bar-cell">'
                        + '<span class="text-' + targetBarColor + '">' + Math.round(b.profit_of_target) + '%</span>'
                        + '<div class="inline-bar-track"><div class="inline-bar-fill ' + targetBarColor + '" style="width:' + Math.min(b.profit_of_target, 100) + '%"></div></div>'
                        + '</div></td>'
                        + '<td><span class="chip chip-sm ' + statusClass + '">' + b.track_status + '</span></td>'
                        + '<td class="col-right ' + (b.drift >= 0 ? 'text-green' : 'text-red') + '">$' + numberFmt(b.drift) + '</td>'
                        + '<td class="col-right">' + b.days_remaining + 'd</td>'
                        + '<td class="col-right text-dim hide-mobile">' + b.base_success.toFixed(1) + '%</td>'
                        + '</tr>';
                }
                tbody.innerHTML = html;
            }

            // Pagination
            if (pagination) {
                if (pages <= 1) {
                    pagination.innerHTML = '';
                } else {
                    var pHtml = '<div class="pagination-bar">';
                    pHtml += '<button class="pagination-btn' + (page <= 1 ? ' disabled' : '') + '" onclick="botPage(' + planId + ',' + (page - 1) + ')"' + (page <= 1 ? ' disabled' : '') + '>&lsaquo; Prev</button>';
                    pHtml += '<span class="pagination-info">Page ' + page + ' of ' + pages + '</span>';
                    pHtml += '<button class="pagination-btn' + (page >= pages ? ' disabled' : '') + '" onclick="botPage(' + planId + ',' + (page + 1) + ')"' + (page >= pages ? ' disabled' : '') + '>Next &rsaquo;</button>';
                    pHtml += '</div>';
                    pagination.innerHTML = pHtml;
                }
            }
        });
    }

    // Global functions for onclick handlers
    window.botPage = function(planId, page) {
        botTableState[planId].page = page;
        loadBotTable(planId);
    };

    function numberFmt(n) {
        return parseFloat(n).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    function nexusEscapeHtml(str) {
        if (!str) return '';
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(str));
        return div.innerHTML;
    }

    // Sort headers
    document.querySelectorAll('.bot-ajax-sort').forEach(function(th) {
        th.style.cursor = 'pointer';
        th.addEventListener('click', function() {
            var planId = this.dataset.plan;
            var sortKey = this.dataset.sort;
            var state = botTableState[planId] || {};

            if (state.sort === sortKey) {
                state.dir = state.dir === 'desc' ? 'asc' : 'desc';
            } else {
                state.sort = sortKey;
                state.dir = 'desc';
            }
            state.page = 1;
            botTableState[planId] = state;

            // Update header indicators
            this.closest('thead').querySelectorAll('.bot-ajax-sort').forEach(function(h) {
                h.classList.remove('sort-asc', 'sort-desc');
            });
            this.classList.add('sort-' + state.dir);

            loadBotTable(planId);
        });
    });

    // Search with debounce
    var searchTimers = {};
    document.querySelectorAll('.bot-search-input').forEach(function(input) {
        input.addEventListener('input', function() {
            var planId = this.dataset.plan;
            clearTimeout(searchTimers[planId]);
            searchTimers[planId] = setTimeout(function() {
                botTableState[planId] = botTableState[planId] || {};
                botTableState[planId].search = input.value;
                botTableState[planId].page = 1;
                loadBotTable(planId);
            }, 300);
        });
    });

    // Limit selector
    document.querySelectorAll('.bot-limit-select').forEach(function(select) {
        select.addEventListener('change', function() {
            var planId = this.dataset.plan;
            botTableState[planId] = botTableState[planId] || {};
            botTableState[planId].limit = parseInt(this.value);
            botTableState[planId].page = 1;
            loadBotTable(planId);
        });
    });

    // Load all plan tables on page load
    @foreach ($plans as $plan)
        loadBotTable({{ $plan['plan_id'] }});
    @endforeach

    // ── Settled bots client-side pagination ──
    (function() {
        var tbody = document.getElementById('settledTableBody');
        if (!tbody) return;

        var allRows = Array.prototype.slice.call(tbody.querySelectorAll('tr'));
        var total = allRows.length;
        if (total === 0) return;

        var perPageSelect = document.getElementById('settledPerPage');
        var pagination = document.getElementById('settledPagination');
        var prevBtn = document.getElementById('settledPrev');
        var nextBtn = document.getElementById('settledNext');
        var pageDisplay = document.getElementById('settledCurrentPage');
        var pagesDisplay = document.getElementById('settledTotalPages');
        var page = 1;

        function getPerPage() {
            var v = perPageSelect.value;
            return v === 'all' ? total : parseInt(v, 10);
        }

        function render() {
            var perPage = getPerPage();
            var totalPages = Math.ceil(total / perPage);
            if (page > totalPages) page = totalPages;
            if (page < 1) page = 1;

            var start = (page - 1) * perPage;
            var end = start + perPage;

            for (var i = 0; i < allRows.length; i++) {
                allRows[i].style.display = (i >= start && i < end) ? '' : 'none';
            }

            if (totalPages > 1) {
                pagination.style.display = '';
                pageDisplay.textContent = page;
                pagesDisplay.textContent = totalPages;
                prevBtn.disabled = page <= 1;
                prevBtn.classList.toggle('disabled', page <= 1);
                nextBtn.disabled = page >= totalPages;
                nextBtn.classList.toggle('disabled', page >= totalPages);
            } else {
                pagination.style.display = 'none';
            }
        }

        perPageSelect.addEventListener('change', function() { page = 1; render(); });
        prevBtn.addEventListener('click', function() { if (page > 1) { page--; render(); } });
        nextBtn.addEventListener('click', function() { page++; render(); });

        render();
    })();

});
</script>
@endsection
