@extends('nexus.layouts.app')

@section('page-title', 'Markets')
@section('sys-mode', 'MARKET ANALYTICS')

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

@section('content')

    @php
        $dateStart = $dates['start'] ?? now()->startOfMonth()->toDateString();
        $dateEnd = $dates['end'] ?? now()->toDateString();
        $isToday = $dateStart === now()->toDateString() && $dateEnd === now()->toDateString();

        if ($isToday) {
            $periodSuffix = 'Today';
        } elseif ($dateStart === now()->subDay()->toDateString() && $dateEnd === now()->subDay()->toDateString()) {
            $periodSuffix = 'Yesterday';
        } elseif ($dateStart === $dateEnd) {
            $periodSuffix = \Carbon\Carbon::parse($dateStart)->format('M j');
        } else {
            $periodSuffix = \Carbon\Carbon::parse($dateStart)->format('M Y');
        }

        $currentMonth = request()->input('month', now()->format('Y-m'));
        $activeRange = request()->input('range', '');

        // Count inactive markets (zero evaluations)
        $inactiveCount = 0;
        $activeMarketRows = [];
        $inactiveMarketRows = [];
        foreach (($marketWinRates ?? []) as $m) {
            if (($m['total_sells'] ?? 0) === 0) {
                $inactiveCount++;
                $inactiveMarketRows[] = $m;
            } else {
                $activeMarketRows[] = $m;
            }
        }
    @endphp

    {{-- PAGE HEADER --}}
    <div class="page-header">
        <div>
            <h1>MARKET <em>ANALYTICS</em></h1>
            <p class="page-header-sub">Dynamic pricing, win rates, and economy indicators</p>
        </div>
        <div class="page-header-right">
            <div class="date-controls">
                <div class="month-selector" id="monthSelector">
                    <button type="button" class="month-selector-btn" id="monthSelectorBtn">
                        {{ \Carbon\Carbon::parse($dateStart)->format('F Y') }}
                    </button>
                    <div class="month-selector-dropdown" id="monthSelectorDropdown">
                        @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 class="quick-filters">
                    <button type="button" class="quick-filter {{ $activeRange === 'today' ? 'active' : '' }}" data-range="today">Today</button>
                    <button type="button" class="quick-filter {{ $activeRange === 'yesterday' ? 'active' : '' }}" data-range="yesterday">Yesterday</button>
                    <button type="button" class="quick-filter {{ $activeRange === '7days' ? 'active' : '' }}" data-range="7days">7 Days</button>
                </div>
            </div>
        </div>
    </div>

    {{-- ECONOMY INDICATORS --}}
    <div class="section-header">
        <span class="section-label">Economy Indicators</span>
    </div>

    @php $indicators = $economyIndicators ?? []; @endphp

    @if (count($indicators) > 0)
        <div class="health-grid">
            @foreach ($indicators as $key => $indicator)
                @php
                    $iValue = $indicator['value'] ?? 0;
                    $iLabel = $indicator['label'] ?? 'Unknown';
                    $iColor = $indicator['color'] ?? 'grey';
                    $iPct = min($iValue * 100, 100);
                    $displayName = ucwords(str_replace('_', ' ', $key));
                @endphp
                <div class="health-cell">
                    <div class="stat-label">{{ $displayName }}</div>
                    <div class="stat-value {{ $iColor }}">{{ number_format($iValue * 100, 1) }}%</div>
                    <div class="stat-sub">{{ $iLabel }}</div>
                    <div class="health-bar-track">
                        <div class="health-bar-fill {{ $iColor }}" style="width: {{ $iPct }}%"></div>
                    </div>
                </div>
            @endforeach
        </div>
    @else
        <div class="empty-state"><span class="empty-state-text">No economy data yet</span></div>
    @endif

    {{-- DYNAMIC PRICING HISTORY --}}
    <div class="section-header">
        <span class="section-label">Dynamic Pricing History (7 Days)</span>
    </div>

    <div class="chart-row" style="grid-template-columns: 1fr;">
        <div class="chart-panel" style="border-right: none;">
            <div class="chart-wrap h300"><canvas id="pricingChart"></canvas></div>
        </div>
    </div>

    {{-- MARKET WIN RATES --}}
    <div class="section-header" style="flex-wrap: wrap; gap: 8px;">
        <span class="section-label">Market Win Rates</span>
        <div style="display: flex; align-items: center; gap: 16px; flex-wrap: wrap;">
            <span class="section-right" style="margin: 0;">{{ $periodSuffix }}</span>
            @if ($inactiveCount > 0)
                <label class="toggle-inline" id="inactiveToggle" onclick="nexus.toggleInactiveMarkets()">
                    <span class="toggle-inline-check"></span>
                    <span class="toggle-inline-label">Show inactive <span class="toggle-inline-count">({{ $inactiveCount }} hidden)</span></span>
                </label>
            @endif
            <a href="/nexus/api/markets/win-rates/export?start={{ $dateStart }}&end={{ $dateEnd }}" class="btn-export">EXPORT CSV</a>
        </div>
    </div>

    @if (count($activeMarketRows) > 0 || count($inactiveMarketRows) > 0)
        <div class="data-table-wrap">
            <table class="data-table" id="marketWinRatesTable">
                <thead><tr><th>#</th><th>Market</th><th class="col-right">Evaluated</th><th class="col-right">Won</th><th class="col-right">Lost</th><th class="col-right">Win Rate</th></tr></thead>
                <tbody>
                    @php $rowIdx = 0; @endphp
                    @foreach ($activeMarketRows as $market)
                        @php
                            $rowIdx++;
                            $mRate = $market['win_rate'] ?? 0;
                            $mTotal = $market['total_sells'] ?? 0;
                        @endphp
                        <tr>
                            <td class="col-num">{{ str_pad($rowIdx, 2, '0', STR_PAD_LEFT) }}</td>
                            <td>{{ $market['market_name'] ?? 'Unknown' }}</td>
                            <td class="col-right text-dim">{{ $mTotal }}</td>
                            <td class="col-right text-green">{{ $market['wins'] ?? 0 }}</td>
                            <td class="col-right text-red">{{ $market['losses'] ?? 0 }}</td>
                            <td class="col-right {{ $mRate >= 50 ? 'text-green' : ($mRate >= 30 ? 'text-yellow' : 'text-red') }}">{{ $mRate }}%</td>
                        </tr>
                    @endforeach
                    @foreach ($inactiveMarketRows as $market)
                        @php $rowIdx++; @endphp
                        <tr class="inactive-market-row" style="display: none;">
                            <td class="col-num text-dim">{{ str_pad($rowIdx, 2, '0', STR_PAD_LEFT) }}</td>
                            <td class="text-dim">{{ $market['market_name'] ?? 'Unknown' }}</td>
                            <td class="col-right text-dim">0</td>
                            <td class="col-right text-dim">0</td>
                            <td class="col-right text-dim">0</td>
                            <td class="col-right text-dim">-</td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    @else
        <div class="empty-state"><span class="empty-state-text">No win rate data for this period</span></div>
    @endif

    {{-- CATEGORY ACTIVITY --}}
    <div class="section-header" style="flex-wrap: wrap; gap: 8px;">
        <span class="section-label">Category Activity</span>
        <div style="display: flex; align-items: center; gap: 16px;">
            <span class="section-right" style="margin: 0;">{{ $periodSuffix }}</span>
            <a href="/nexus/api/markets/categories/export?start={{ $dateStart }}&end={{ $dateEnd }}" class="btn-export">EXPORT CSV</a>
        </div>
    </div>

    @if (!empty($categoryActivity) && count($categoryActivity) > 0)
        <div class="data-table-wrap">
            <table class="data-table">
                <thead><tr><th>Category</th><th class="col-right">Bids</th><th class="col-right">Sells</th><th class="col-right">Total</th></tr></thead>
                <tbody>
                    @foreach ($categoryActivity as $cat)
                        <tr>
                            <td>{{ $cat['category'] ?? 'Unknown' }}</td>
                            <td class="col-right text-orange">{{ number_format($cat['bids'] ?? 0) }}</td>
                            <td class="col-right text-grey">{{ number_format($cat['sells'] ?? 0) }}</td>
                            <td class="col-right">{{ number_format(($cat['bids'] ?? 0) + ($cat['sells'] ?? 0)) }}</td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    @else
        <div class="empty-state"><span class="empty-state-text">No category 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;

        /* ── Dynamic Pricing History ── */
        var pricingCtx = document.getElementById('pricingChart');
        if (pricingCtx) {
            var pricingRaw = @json($pricingHistory ?? []);

            var activeMarkets = pricingRaw.filter(function(market) {
                var base = market.base_margin;
                var dailyData = market.daily_data || [];
                return dailyData.some(function(d) {
                    return Math.abs(d.margin - base) > 0.01;
                });
            });

            if (activeMarkets.length === 0) activeMarkets = pricingRaw;

            var colors = ['#e8842a', '#00aa00', '#f5f5f5', '#cc0000', '#ccaa00', '#999999', '#e85d75', '#5da8e8', '#a8e85d', '#d4771e'];

            var labels = [];
            if (activeMarkets.length > 0 && activeMarkets[0].daily_data) {
                labels = activeMarkets[0].daily_data.map(function(d) { return d.date; });
            }

            var datasets = activeMarkets.map(function(market, i) {
                var data = (market.daily_data || []).map(function(d) { return d.margin; });
                return {
                    label: market.market_name || 'Market',
                    data: data,
                    borderColor: colors[i % colors.length],
                    borderWidth: 2,
                    tension: 0.3,
                    pointRadius: 2,
                    pointHitRadius: 10,
                    pointBackgroundColor: colors[i % colors.length],
                    fill: false,
                };
            });

            new Chart(pricingCtx, {
                type: 'line',
                data: { labels: labels, datasets: datasets },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { position: 'bottom', labels: { padding: 16, usePointStyle: true, pointStyle: 'line', font: { size: 10 } } },
                        tooltip: { backgroundColor: '#141414', borderColor: '#222222', borderWidth: 1, cornerRadius: 4, callbacks: { label: function(ctx) { return ctx.dataset.label + ': ' + ctx.parsed.y.toFixed(2) + '%'; } } }
                    },
                    scales: {
                        x: { grid: { display: false }, ticks: { font: { size: 9 }, maxTicksLimit: 7 } },
                        y: { grid: { color: '#222222', drawBorder: false }, ticks: { font: { size: 9 }, callback: function(v) { return v + '%'; } }, title: { display: true, text: 'Sell Margin %', font: { size: 9 }, color: '#7a7a7a' } }
                    }
                }
            });
        }

        /* ── Month selector + Quick filters ── */
        nexus.initMonthSelector('monthSelector', '/nexus/markets');
        nexus.initQuickFilters('/nexus/markets');
    });
</script>
@endsection
