@model List<SicboSub.Web.Models.RankingHistoryItem>
@{
    Layout = "_GameLayout";
}
@using SicboSub.Web.Language;
@section Styles {
    <link rel="stylesheet" href="~/css/sicbo-ranking.css" />
}

<div class="home">
    <!-- Background Image -->
    <img class="image" src="~/img/image-2.png" />
    
    <!-- Reuse Game Menu -->
    <partial name="_GameMenu" />

    <!-- Ranking Content Panel -->
    <div class="ranking-panel">
        <!-- Corner Rectangle -->
        <img class="panel-corner-rectangle" src="~/img/Rectangle_Blue_T.png" alt="" />
        <!-- Header -->
        <div class="ranking-header">
            <!-- Triangles -->
            <div class="header-triangles">
                <span class="triangle white">▲</span>
                <span class="triangle blue">▲</span>
            </div>
            
            <!-- Switch Button -->
            <a href="@Url.Action("DailyRanking", "Home")" class="switch-button">
                <img class="switch-icon" src="~/img/017-strategy.png" alt="" />
                <span class="switch-text">@Language.SwitchToDaily</span>
            </a>
            
            <!-- Date Filter (Month) -->
            <div class="ranking-date-container">
                @{
                    var selectedDateStr = ViewData["SelectedDate"] as string;
                    var displayDate = DateTime.Now;
                    // If yyyy-MM
                    if (!string.IsNullOrEmpty(selectedDateStr))
                    {
                        if (DateTime.TryParseExact(selectedDateStr, "yyyy-MM", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime parsed))
                        {
                            displayDate = parsed;
                        }
                    }
                }
                <!-- Trigger Button -->
                <div class="date-trigger-btn" onclick="openMonthCalendar()">
                    <span id="dateTriggerText" class="date-trigger-text">@displayDate.ToString("MM/yyyy")</span>
                    <svg class="date-trigger-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                         <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                         <line x1="16" y1="2" x2="16" y2="6"></line>
                         <line x1="8" y1="2" x2="8" y2="6"></line>
                         <line x1="3" y1="10" x2="21" y2="10"></line>
                    </svg>
                </div>
            </div>

            <!-- Title -->
            <div class="ranking-title monthly">
                <span class="title-line">@Language.Monthly</span>
                <span class="title-line">@Language.Winner</span>
            </div>
        </div>

        <!-- Custom Month Popup -->
        <div id="monthCalendarPopup" class="calendar-popup-overlay" style="display: none;">
            <div class="calendar-popup">
                <button class="calendar-close-btn" onclick="closeMonthCalendar()">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                </button>
                
                <div class="calendar-header">
                    <button class="month-nav-btn" onclick="changeYear(-1)">&lt;</button>
                    <span id="currentYearLabel" class="current-month-label">2026</span>
                    <button class="month-nav-btn" onclick="changeYear(1)">&gt;</button>
                </div>
                
                <!-- Month Grid -->
                <div class="calendar-grid" style="grid-template-columns: repeat(3, 1fr); gap: 12px;">
                    <!-- Months injected here -->
                    <div id="calendarMonthsContainer" style="display: contents;"></div>
                </div>
            </div>
        </div>

        <script>
            let currentYear = new Date('@displayDate.ToString("yyyy-MM-01")').getFullYear();
            let selectedMonthDate = new Date('@displayDate.ToString("yyyy-MM-01")');

            function openMonthCalendar() {
                renderMonthCalendar();
                document.getElementById('monthCalendarPopup').style.display = 'flex';
            }

            function closeMonthCalendar() {
                document.getElementById('monthCalendarPopup').style.display = 'none';
            }
            
            // Close on overlay click
            document.getElementById('monthCalendarPopup').addEventListener('click', function(e) {
                if (e.target === this) closeMonthCalendar();
            });

            function changeYear(delta) {
                currentYear += delta;
                renderMonthCalendar();
            }

            function renderMonthCalendar() {
                document.getElementById('currentYearLabel').textContent = currentYear;

                const container = document.getElementById('calendarMonthsContainer');
                container.innerHTML = '';
                
                const monthNames = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];

                for (let i = 0; i < 12; i++) {
                    const monthEl = document.createElement('div');
                    monthEl.className = 'calendar-day'; // reuse styles
                    monthEl.style.borderRadius = '12px'; // slightly different shape
                    monthEl.style.aspectRatio = '2/1';
                    monthEl.textContent = monthNames[i];
                    
                    // Check if selected
                    if (currentYear === selectedMonthDate.getFullYear() && 
                        i === selectedMonthDate.getMonth()) {
                        monthEl.classList.add('selected');
                    }

                    monthEl.onclick = function() {
                        selectMonth(currentYear, i);
                    };

                    container.appendChild(monthEl);
                }
            }

            function selectMonth(year, month) {
                // Format yyyy-MM
                const monthStr = (month + 1).toString().padStart(2, '0');
                const dateStr = `${year}-${monthStr}`;
                
                // Redirect
                window.location.href = '@Url.Action("MonthlyRanking", "Home")?date=' + dateStr;
            }
        </script>

        <!-- Table Header -->
        <div class="ranking-table-header">
            <div class="col-top">@Language.Top</div>
            <div class="col-player">@Language.Player</div>
            <div class="col-player">@Language.Time</div>
            <div class="col-rewards">@Language.Rewards</div>
        </div>

        <!-- Table Body -->
        <div class="ranking-table-body">
            @if (Model != null && Model.Count > 0)
            {
                int top = 1;
                foreach (var item in Model)
                {
                    var rowClass = "";
                    if (top == 1) rowClass = "gold";
                    else if (top == 2) rowClass = "silver";
                    else if (top == 3) rowClass = "bronze";

                    <div class="ranking-row @rowClass">
                        <div class="col-top">@item.rankPosition</div>
                        @* <div class="col-player">@(string.IsNullOrEmpty(item.msisdn) ? "****" : item.msisdn)</div> *@
                        <div class="col-player">
                            @(string.IsNullOrEmpty(item.msisdn) ? "****" :
                                                item.msisdn.Substring(0, 3) + "****" + item.msisdn.Substring(item.msisdn.Length - 3))
                        </div>
                        <div class="col-player">@item.rankDate.ToString("dd/MM/yyyy")</div>
                        <div class="col-rewards">
                            <span class="reward-value">+@item.rewardValue.ToString("N0")</span> 
                            <span class="reward-unit">@item.rewardUnit</span>
                        </div>
                    </div>
                    top++;
                }
            }
            else
            {
                <div class="ranking-row" style="justify-content:center;">
                    <span></span>
                </div>
            }
        </div>
    </div>
</div>
