@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_red_T.png" alt="" />
        <!-- Header -->
        <div class="ranking-header">
            <!-- Triangles -->
            <div class="header-triangles">
                <span class="triangle red">▲</span>
                <span class="triangle red">▲</span>
            </div>
            
            <!-- Switch Button -->
            <a href="@Url.Action("MonthlyRanking", "Home")" class="switch-button">
                <img class="switch-icon" src="~/img/017-strategy.png" alt="" />
                <span class="switch-text">@Language.SwitchToMonthly</span>
            </a>

            <!-- Date Filter -->
            <div class="ranking-date-container">
                @{
                    var selectedDateStr = ViewData["SelectedDate"] as string;
                    var displayDate = DateTime.Now;
                    if (!string.IsNullOrEmpty(selectedDateStr) && DateTime.TryParse(selectedDateStr, out DateTime parsed))
                    {
                        displayDate = parsed;
                    }
                }
                <!-- Trigger Button -->
                <div class="date-trigger-btn" onclick="openCalendar()">
                    <span id="dateTriggerText" class="date-trigger-text">@displayDate.ToString("MM/dd/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 daily">
                <span class="title-line">@Language.Daily</span>
                <span class="title-line">@Language.Winner</span>
            </div>
        </div>

        <!-- Custom Calendar Popup -->
        <div id="calendarPopup" class="calendar-popup-overlay" style="display: none;">
            <div class="calendar-popup">
                <button class="calendar-close-btn" onclick="closeCalendar()">
                    <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="changeMonth(-1)">&lt;</button>
                    <span id="currentMonthLabel" class="current-month-label">JANUARY 2026</span>
                    <button class="month-nav-btn" onclick="changeMonth(1)">&gt;</button>
                </div>
                
                <div class="calendar-grid">
                    <div class="calendar-day-header">Mon</div>
                    <div class="calendar-day-header">Tue</div>
                    <div class="calendar-day-header">Wed</div>
                    <div class="calendar-day-header">Thu</div>
                    <div class="calendar-day-header">Fri</div>
                    <div class="calendar-day-header">Sat</div>
                    <div class="calendar-day-header sunday">Sun</div>
                    
                    <!-- Days will be injected here -->
                    <div id="calendarDaysContainer" style="display: contents;"></div>
                </div>
            </div>
        </div>

        <script>
            let currentCalendarDate = new Date('@displayDate.ToString("yyyy-MM-dd")');
            let selectedDate = new Date('@displayDate.ToString("yyyy-MM-dd")');

            function openCalendar() {
                renderCalendar();
                document.getElementById('calendarPopup').style.display = 'flex';
            }

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

            function changeMonth(delta) {
                currentCalendarDate.setMonth(currentCalendarDate.getMonth() + delta);
                renderCalendar();
            }

            function renderCalendar() {
                const year = currentCalendarDate.getFullYear();
                const month = currentCalendarDate.getMonth();
                const today = new Date();

                // Update Header
                const monthNames = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
                document.getElementById('currentMonthLabel').textContent = `${monthNames[month]} ${year}`;

                const container = document.getElementById('calendarDaysContainer');
                container.innerHTML = '';

                // Get first day of month
                const firstDay = new Date(year, month, 1);
                // Adjust for Mon start (0 is Sun, 1 is Mon)
                // We want Mon=0, Sun=6
                let startDay = firstDay.getDay() - 1; 
                if (startDay === -1) startDay = 6;

                const daysInMonth = new Date(year, month + 1, 0).getDate();

                // Empty slots
                for (let i = 0; i < startDay; i++) {
                    const empty = document.createElement('div');
                    empty.className = 'calendar-day empty';
                    container.appendChild(empty);
                }

                // Days
                for (let i = 1; i <= daysInMonth; i++) {
                    const dayEl = document.createElement('div');
                    dayEl.className = 'calendar-day';
                    dayEl.textContent = i;
                    
                    // Check if selected
                    if (year === selectedDate.getFullYear() && 
                        month === selectedDate.getMonth() && 
                        i === selectedDate.getDate()) {
                        dayEl.classList.add('selected');
                    }

                    dayEl.onclick = function() {
                        selectDate(year, month, i);
                    };

                    container.appendChild(dayEl);
                }
            }

            function selectDate(year, month, day) {
                // Format yyyy-MM-dd for controller
                // Javascript months are 0-indexed
                const monthStr = (month + 1).toString().padStart(2, '0');
                const dayStr = day.toString().padStart(2, '0');
                const dateStr = `${year}-${monthStr}-${dayStr}`;
                
                // Redirect
                window.location.href = '@Url.Action("DailyRanking", "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>
