@extends('nexus.layouts.app')

@section('page-title', 'Controls')
@section('sys-mode', 'ADMIN CONTROLS')

@section('content')

    @php
        /*
         * HUMAN LABEL MAP
         * Maps actual database config keys to human-readable labels and units.
         * Source: live server screenshot (March 9, 2026).
         * Keys not in this map fall back to ucwords(str_replace('_', ' ', $key)).
         */
        $humanMap = [
            // General
            'nexus_status'              => ['label' => 'Engine Status',              'unit' => ''],
            'nexus_version'             => ['label' => 'Engine Version',             'unit' => ''],
            'nexus_go_live_date'        => ['label' => 'Target Go-Live',             'unit' => ''],
            'emergency_pause'           => ['label' => 'Emergency Pause',            'unit' => ''],
            'first_timer_guarantee'     => ['label' => 'First-Timer Guarantee',      'unit' => ''],

            // Session
            'session_1_start_utc'       => ['label' => 'Session 1 Start',            'unit' => 'UTC'],
            'session_2_start_utc'       => ['label' => 'Session 2 Start',            'unit' => 'UTC'],
            'session_3_start_utc'       => ['label' => 'Session 3 Start',            'unit' => 'UTC'],
            'session_duration_minutes'  => ['label' => 'Session Duration',           'unit' => 'mins'],
            'criteria_rotation_enabled' => ['label' => 'Criteria Rotation',          'unit' => ''],

            // Win Rate
            'win_rate_session_1'        => ['label' => 'Win Rate Session 1',         'unit' => '%'],
            'win_rate_session_2'        => ['label' => 'Win Rate Session 2',         'unit' => '%'],
            'win_rate_session_3'        => ['label' => 'Win Rate Session 3',         'unit' => '%'],

            // Loss
            'loss_requirement_min'      => ['label' => 'Loss Requirement Min',       'unit' => 'losses'],
            'loss_requirement_max'      => ['label' => 'Loss Requirement Max',       'unit' => 'losses'],

            // Economy
            'recess_threshold_percent'  => ['label' => 'Recess Threshold',           'unit' => '%'],
            'excess_threshold_percent'  => ['label' => 'Excess Threshold',           'unit' => '%'],
            'buyback_zone_percent'      => ['label' => 'Buyback Zone',               'unit' => '%'],

            // Economy (pre-go-live review)
            'min_bid_percent'            => ['label' => 'Minimum Bid Floor',           'unit' => '%'],
            'monthly_profit_cap_percent' => ['label' => 'Monthly Profit Cap',          'unit' => '%'],
            'max_sell_margin'            => ['label' => 'Max Sell Margin',             'unit' => '%'],
            'win_rate_ceiling'           => ['label' => 'Win Rate Ceiling',            'unit' => '%'],

            // Economy (cap overhaul)
            'cap_period_days'              => ['label' => 'Cap Window Length',              'unit' => 'days'],
            'weekly_pace_randomness_min'   => ['label' => 'Weekly Budget Randomness Min',   'unit' => 'x'],
            'weekly_pace_randomness_max'   => ['label' => 'Weekly Budget Randomness Max',   'unit' => 'x'],
            'daily_pace_randomness_min'    => ['label' => 'Daily Budget Randomness Min',    'unit' => 'x'],
            'daily_pace_randomness_max'    => ['label' => 'Daily Budget Randomness Max',    'unit' => 'x'],

            // Economy (cap tuning)
            'loss_brake_threshold'         => ['label' => 'Loss Brake Threshold',             'unit' => '%'],
            'daily_budget_floor'           => ['label' => 'Daily Budget Floor',                'unit' => '$'],
            'weekly_budget_floor'          => ['label' => 'Weekly Budget Floor',               'unit' => '$'],

            // Session (dynamic wins per session)
            'max_wins_per_session'       => ['label' => 'Wins Per Session Cap',        'unit' => 'wins'],
            'max_wins_per_session_min'   => ['label' => 'Wins Per Session Min',        'unit' => 'wins'],
            'max_wins_per_session_max'   => ['label' => 'Wins Per Session Max',        'unit' => 'wins'],

            // Bot
            'bot_session_alignment'     => ['label' => 'Session Alignment',          'unit' => ''],
            'bot_fund_range_enforcement'=> ['label' => 'Fund Range Enforcement',     'unit' => ''],
        ];

        /*
         * SECTION DESCRIPTIONS
         * Matches actual database group names from nexus_config table.
         */
        $sectionMeta = [
            'general'   => ['title' => 'General',             'desc' => 'Core engine identity and state. nexus_status controls the master kill switch.'],
            'session'   => ['title' => 'Session Schedule',    'desc' => '3 daily bidding sessions. Times in 24hr UTC format. Duration in minutes.'],
            'winrate'   => ['title' => 'Win Rates',           'desc' => 'Target win rate per session. Session 1 highest (80%), Session 3 lowest (30%).'],
            'loss'      => ['title' => 'Loss Requirements',   'desc' => 'Dynamic loss requirement baseline range. NEXUS sets the actual value per session.'],
            'economy'   => ['title' => 'Economy',             'desc' => 'Dynamic pricing thresholds, profit caps, and pacing budgets. Cap window is per-user rolling.'],
            'bot'       => ['title' => 'Bot Governance',      'desc' => 'AI bot behaviour toggles. Fund ranges are set per-plan in the table below.'],
        ];

        /*
         * SECTION ORDER -- controls page layout.
         * Matches the actual group values in nexus_config table.
         */
        $sectionOrder = ['general', 'session', 'winrate', 'loss', 'economy', 'bot'];

        /*
         * HIDDEN FROM CONFIG LIST
         * emergency_pause is handled by the dedicated toggle at the top.
         */
        $hiddenKeys = ['emergency_pause'];

        /* Sort config groups by defined order */
        $allConfig = $allConfig ?? [];
        $sortedConfig = [];
        foreach ($sectionOrder as $group) {
            if (isset($allConfig[$group])) {
                $sortedConfig[$group] = $allConfig[$group];
            }
        }
        foreach ($allConfig as $group => $configs) {
            if (!isset($sortedConfig[$group])) {
                $sortedConfig[$group] = $configs;
            }
        }

        $isPaused = \App\Nexus\Engine\NexusConfig::get('emergency_pause', '0');
        $isPaused = $isPaused === '1' || $isPaused === 1 || $isPaused === true;
    @endphp


    {{-- PAGE HEADER --}}
    <div class="page-header">
        <div>
            <h1>ADMIN <em>CONTROLS</em></h1>
            <p class="page-header-sub">Engine configuration and emergency overrides</p>
        </div>
        <div class="page-header-right">
            <span class="chip {{ $isPaused ? 'chip-error' : 'chip-live' }}">
                {{ $isPaused ? 'PAUSED' : 'OPERATIONAL' }}
            </span>
        </div>
    </div>


    {{-- ─── EMERGENCY PAUSE ─── --}}

    <div class="section-header">
        <span class="section-label">Emergency Controls</span>
        <span class="section-right">Immediate effect on all trading</span>
    </div>

    <div class="emergency-control-panel">
        <div class="toggle-wrap">
            <div id="pauseToggle"
                 class="toggle-switch {{ $isPaused ? 'on' : '' }}"
                 data-state="{{ $isPaused ? '1' : '0' }}"
                 onclick="nexus.togglePause(this)"></div>
            <span class="toggle-label {{ $isPaused ? 'danger' : '' }}" id="pauseLabel">
                Emergency Pause: {{ $isPaused ? 'ACTIVE' : 'OFF' }}
            </span>
        </div>
        <div class="emergency-control-desc">
            <span class="config-desc">
                When active, all trading operations halt immediately. Sessions will not open, sells will not be evaluated, bids will not be processed. AI bots continue their own cycles unaffected.
            </span>
        </div>
    </div>


    {{-- ─── CONFIG SECTIONS ─── --}}

    @foreach ($sortedConfig as $groupName => $configs)
        @php
            $groupKey = strtolower($groupName);
            $meta = $sectionMeta[$groupKey] ?? ['title' => ucwords(str_replace('_', ' ', $groupName)), 'desc' => ''];
        @endphp

        <div class="config-section">
            <div class="config-section-header">
                <div>
                    <span class="config-section-title">{{ $meta['title'] }}</span>
                    @if ($meta['desc'])
                        <span class="config-section-desc">{{ $meta['desc'] }}</span>
                    @endif
                </div>
            </div>

            @foreach ($configs as $config)
                @php
                    $configKey = $config['key'] ?? ($config->key ?? '');
                    $configValue = $config['value'] ?? ($config->value ?? '');
                    $configDesc = $config['description'] ?? ($config->description ?? '');
                    $isEditable = $config['is_editable'] ?? ($config->is_editable ?? 1);
                    $configType = $config['type'] ?? ($config->type ?? 'string');
                    $isProtected = $configKey === 'nexus_status';

                    /* Skip hidden keys */
                    if (in_array($configKey, $hiddenKeys)) continue;

                    /* Look up human label and unit */
                    $mapped = $humanMap[$configKey] ?? null;
                    $humanLabel = $mapped ? $mapped['label'] : ucwords(str_replace('_', ' ', $configKey));
                    $unit = $mapped ? $mapped['unit'] : '';
                @endphp

                <div class="config-row" id="config-row-{{ $configKey }}">
                    <div class="config-label">
                        <span class="config-human-label">{{ $humanLabel }}</span>
                        <span class="config-key-name">{{ $configKey }}</span>
                        @if ($isProtected)
                            <span class="config-protected-badge">PROTECTED</span>
                        @endif
                    </div>
                    <div class="config-input-wrap">
                        <div class="config-input-group">
                            <input type="text"
                                   class="config-input"
                                   id="input-{{ $configKey }}"
                                   value="{{ $configValue }}"
                                   data-key="{{ $configKey }}"
                                   data-original="{{ $configValue }}"
                                   {{ (!$isEditable || $isProtected) ? 'disabled' : '' }}>
                            @if ($unit)
                                <span class="config-unit">{{ $unit }}</span>
                            @endif
                        </div>
                        @if ($configDesc)
                            <div class="config-desc">{{ $configDesc }}</div>
                        @endif
                        @php
                            $changeInfo = ($configChanges ?? [])[$configKey] ?? null;
                        @endphp
                        @if ($changeInfo)
                            <div class="config-timestamp">
                                Last changed: {{ \Carbon\Carbon::parse($changeInfo['last_changed'])->format('M j, Y H:i') }}
                                @if ($changeInfo['last_actor_id'])
                                    <span class="config-timestamp-actor">by admin #{{ $changeInfo['last_actor_id'] }}</span>
                                @endif
                            </div>
                        @endif
                    </div>
                    <div class="config-action">
                        @if ($isEditable && !$isProtected)
                            <button class="btn-sm btn-save"
                                    onclick="nexus.saveConfig('{{ $configKey }}')"
                                    id="save-{{ $configKey }}"
                                    style="display: none;">
                                SAVE
                            </button>
                        @else
                            <span class="chip chip-sm chip-pending">LOCKED</span>
                        @endif
                    </div>
                </div>
            @endforeach
        </div>
    @endforeach


    {{-- ─── PLAN RANGES ─── --}}

    <div class="section-header" style="margin-top: 20px;">
        <span class="section-label">AI Plan NEXUS Ranges</span>
        <span class="section-right">Bot profit governance parameters</span>
    </div>

    <div style="border-bottom: 1px solid var(--line);">
        {{-- Table header --}}
        <div class="plan-row plan-row-header">
            <div class="plan-name plan-header-cell">Plan</div>
            <div class="plan-input-cell plan-header-cell">Daily Min / Max %</div>
            <div class="plan-input-cell plan-header-cell">Monthly Min / Max %</div>
            <div class="plan-input-cell plan-header-cell" style="border-right: none;">Success Min / Max %</div>
            <div class="plan-header-spacer"></div>
        </div>

        @php $plans = $plans ?? collect(); @endphp

        @foreach ($plans as $plan)
            <div class="plan-row" id="plan-row-{{ $plan->id }}">
                <div class="plan-name">{{ $plan->name }}</div>
                <div class="plan-input-cell">
                    <div class="plan-input-pair">
                        <input type="text" class="plan-input" id="plan-{{ $plan->id }}-daily-min" value="{{ $plan->nexus_daily_min }}" data-original="{{ $plan->nexus_daily_min }}">
                        <span class="plan-input-divider">/</span>
                        <input type="text" class="plan-input" id="plan-{{ $plan->id }}-daily-max" value="{{ $plan->nexus_daily_max }}" data-original="{{ $plan->nexus_daily_max }}">
                    </div>
                </div>
                <div class="plan-input-cell">
                    <div class="plan-input-pair">
                        <input type="text" class="plan-input" id="plan-{{ $plan->id }}-monthly-min" value="{{ $plan->nexus_monthly_min }}" data-original="{{ $plan->nexus_monthly_min }}">
                        <span class="plan-input-divider">/</span>
                        <input type="text" class="plan-input" id="plan-{{ $plan->id }}-monthly-max" value="{{ $plan->nexus_monthly_max }}" data-original="{{ $plan->nexus_monthly_max }}">
                    </div>
                </div>
                <div class="plan-input-cell" style="border-right: none;">
                    <div class="plan-input-pair">
                        <input type="text" class="plan-input" id="plan-{{ $plan->id }}-success-min" value="{{ $plan->nexus_success_rate_min }}" data-original="{{ $plan->nexus_success_rate_min }}">
                        <span class="plan-input-divider">/</span>
                        <input type="text" class="plan-input" id="plan-{{ $plan->id }}-success-max" value="{{ $plan->nexus_success_rate_max }}" data-original="{{ $plan->nexus_success_rate_max }}">
                    </div>
                </div>
                <div class="plan-action-cell">
                    <button class="btn-sm btn-save"
                            onclick="nexus.savePlanRanges({{ $plan->id }})"
                            id="plan-save-{{ $plan->id }}"
                            style="display: none;">
                        SAVE
                    </button>
                </div>
            </div>
        @endforeach
    </div>

@endsection

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

        /* Show SAVE button when config input changes */
        document.querySelectorAll('.config-input:not([disabled])').forEach(function (input) {
            input.addEventListener('input', function () {
                var key = this.dataset.key;
                var saveBtn = document.getElementById('save-' + key);
                if (saveBtn) {
                    saveBtn.style.display = this.value !== this.dataset.original ? 'inline-block' : 'none';
                }
            });
        });

        /* Show SAVE button when plan input changes */
        document.querySelectorAll('.plan-input').forEach(function (input) {
            input.addEventListener('input', function () {
                var id = this.id;
                var parts = id.split('-');
                var planId = parts[1];
                var saveBtn = document.getElementById('plan-save-' + planId);
                if (saveBtn) saveBtn.style.display = 'inline-block';
            });
        });

    });
</script>
@endsection
