@extends('layouts.app')

@section('content')
<style>
/* Colores personalizados basados en Blulinc */
:root {
    --blulinc-black: #000000;
    --blulinc-blue: #015cff;
    --blulinc-gray: #c1c1c1;
    --blulinc-light-gray: #f8f9fa;
    --blulinc-light-blue: #e6f2ff;
    --blulinc-bg-blue: #f0f7ff;
    --blulinc-success: #4CAF50;
    --blulinc-warning: #FF9800;
    --blulinc-danger: #f44336;
    --blulinc-sky: #87ceeb;
}

body {
    background-color: var(--blulinc-bg-blue) !important;
}

/* Dashboard Container */
.dashboard-container {
    max-width: 1800px;
    margin: 0 auto;
    padding: 12px;
    width: 98%;
}

/* Welcome Popup */
.welcome-popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.7);
    z-index: 9999;
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    animation: fadeIn 0.5s ease-in-out forwards;
}

.welcome-popup.hide {
    animation: fadeOut 0.5s ease-in-out forwards;
}

.welcome-content {
    background: white;
    border-radius: 16px;
    padding: 40px;
    text-align: center;
    max-width: 500px;
    width: 90%;
    box-shadow: 0 20px 60px rgba(1, 92, 255, 0.3);
    transform: scale(0.8);
    animation: popIn 0.6s ease-out 0.2s forwards;
}

.welcome-title {
    color: var(--blulinc-blue);
    font-size: 28px;
    font-weight: 700;
    margin-bottom: 16px;
}

.welcome-message {
    color: var(--blulinc-gray);
    font-size: 16px;
    margin-bottom: 30px;
}

.welcome-btn {
    background: linear-gradient(135deg, var(--blulinc-blue) 0%, #0146cc 100%);
    color: white;
    border: none;
    padding: 12px 30px;
    border-radius: 8px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
}

.welcome-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(1, 92, 255, 0.4);
}

/* Dashboard Header */
.dashboard-header {
    text-align: center;
    margin-bottom: 16px;
    opacity: 0;
    transform: translateY(30px);
    animation: slideUp 0.8s ease-out 1.2s forwards;
}

.dashboard-title {
    color: var(--blulinc-blue);
    font-size: 28px;
    font-weight: 700;
    margin-bottom: 4px;
}

.dashboard-subtitle {
    color: var(--blulinc-gray);
    font-size: 14px;
}

/* Main Grid Layout */
.main-grid {
    display: grid;
    grid-template-columns: 1fr 350px;
    gap: 16px;
    margin-bottom: 16px;
    opacity: 0;
    animation: slideUp 0.8s ease-out 1.4s forwards;
}

/* KPI Cards Grid */
.kpi-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 12px;
    margin-bottom: 16px;
}

.kpi-card {
    background: white;
    border-radius: 10px;
    padding: 16px;
    box-shadow: 0 4px 20px rgba(1, 92, 255, 0.1);
    border: 1px solid #e1ecf7;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.kpi-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(135deg, var(--blulinc-blue), var(--blulinc-sky));
}

.kpi-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 30px rgba(1, 92, 255, 0.2);
}

.kpi-icon {
    font-size: 24px;
    color: var(--blulinc-blue);
    margin-bottom: 8px;
}

.kpi-value {
    font-size: 22px;
    font-weight: 700;
    color: var(--blulinc-black);
    margin-bottom: 2px;
}

.kpi-label {
    font-size: 12px;
    color: var(--blulinc-gray);
    text-transform: uppercase;
    letter-spacing: 0.3px;
}

/* Sidebar Chart Container */
.sidebar-chart {
    background: white;
    border-radius: 10px;
    padding: 16px;
    box-shadow: 0 4px 20px rgba(1, 92, 255, 0.1);
    border: 1px solid #e1ecf7;
    display: flex;
    flex-direction: column;
    height: fit-content;
}

.sidebar-chart .chart-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--blulinc-black);
    margin-bottom: 12px;
    text-align: center;
    flex-shrink: 0;
}

.sidebar-chart .chart-canvas {
    position: relative;
    height: 250px;
}

/* Bottom Grid Layout - Tendencias y Gestión lado a lado */
.bottom-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    opacity: 0;
    animation: slideUp 0.8s ease-out 1.6s forwards;
}

/* Half Width Chart Container */
.half-width-chart {
    background: white;
    border-radius: 10px;
    padding: 16px;
    box-shadow: 0 4px 20px rgba(1, 92, 255, 0.1);
    border: 1px solid #e1ecf7;
}

.half-width-chart .chart-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--blulinc-black);
    margin-bottom: 12px;
    text-align: center;
}

.half-width-chart .chart-canvas {
    position: relative;
    height: 250px;
}

/* User Management Section - Rediseñada para layout horizontal */
.management-section {
    background: white;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 4px 20px rgba(1, 92, 255, 0.1);
    border: 1px solid #e1ecf7;
    display: flex;
    flex-direction: column;
    justify-content: center;
    text-align: center;
    height: 100%;
}

.management-section h3 {
    color: var(--blulinc-blue);
    margin-bottom: 12px;
    font-size: 20px;
    font-weight: 700;
}

.management-section p {
    color: var(--blulinc-gray);
    margin-bottom: 18px;
    font-size: 14px;
    line-height: 1.4;
}

.management-btn {
    background: linear-gradient(135deg, var(--blulinc-blue) 0%, #0146cc 100%);
    color: white;
    border: none;
    padding: 12px 24px;
    border-radius: 8px;
    font-weight: 600;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    transition: all 0.3s ease;
    justify-self: center;
    align-self: center;
}

.management-btn:hover {
    color: white;
    text-decoration: none;
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(1, 92, 255, 0.4);
}

/* Animations */
@keyframes fadeIn {
    to { opacity: 1; }
}

@keyframes fadeOut {
    to { opacity: 0; visibility: hidden; }
}

@keyframes popIn {
    to { transform: scale(1); }
}

@keyframes slideUp {
    to { 
        opacity: 1; 
        transform: translateY(0); 
    }
}

/* Responsive Design */
@media (max-width: 400px) {
    .dashboard-container {
        padding: 4px;
    }
    
    .dashboard-title {
        font-size: 18px;
    }
    
    .dashboard-subtitle {
        font-size: 10px;
    }
    
    .kpi-grid {
        grid-template-columns: 1fr;
        gap: 4px;
    }
    
    .kpi-card {
        padding: 8px;
    }
    
    .kpi-icon {
        font-size: 16px;
        margin-bottom: 3px;
    }
    
    .kpi-value {
        font-size: 14px;
    }
    
    .kpi-label {
        font-size: 8px;
    }
    
    .sidebar-chart .chart-canvas,
    .half-width-chart .chart-canvas {
        height: 140px;
    }
    
    .sidebar-chart, .half-width-chart, .management-section {
        padding: 8px;
    }
    
    .sidebar-chart .chart-title,
    .half-width-chart .chart-title {
        font-size: 12px;
        margin-bottom: 4px;
    }
    
    .management-section h3 {
        font-size: 14px;
        margin-bottom: 4px;
    }
    
    .management-section p {
        font-size: 10px;
        margin-bottom: 8px;
    }
    
    .management-btn {
        padding: 6px 12px;
        font-size: 10px;
    }
}

@media (max-width: 1200px) {
    .main-grid {
        grid-template-columns: 1fr;
        gap: 14px;
    }
    
    .bottom-grid {
        grid-template-columns: 1fr;
        gap: 14px;
    }
    
    .sidebar-chart .chart-canvas {
        height: 220px;
    }
    
    .half-width-chart .chart-canvas {
        height: 220px;
    }
    
    .kpi-grid {
        grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
        gap: 10px;
    }
}

@media (max-width: 768px) {
    .dashboard-container {
        padding: 8px;
    }
    
    .dashboard-header {
        margin-bottom: 12px;
    }
    
    .dashboard-title {
        font-size: 24px;
        margin-bottom: 2px;
    }
    
    .dashboard-subtitle {
        font-size: 12px;
    }
    
    .main-grid, .bottom-grid {
        gap: 10px;
    }
    
    .kpi-grid {
        grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
        gap: 8px;
        margin-bottom: 10px;
    }
    
    .kpi-card {
        padding: 12px;
    }
    
    .kpi-icon {
        font-size: 20px;
        margin-bottom: 6px;
    }
    
    .kpi-value {
        font-size: 18px;
    }
    
    .kpi-label {
        font-size: 10px;
    }
    
    .sidebar-chart, .half-width-chart, .management-section {
        padding: 12px;
    }
    
    .sidebar-chart .chart-canvas,
    .half-width-chart .chart-canvas {
        height: 180px;
    }
    
    .sidebar-chart .chart-title,
    .half-width-chart .chart-title {
        font-size: 14px;
        margin-bottom: 8px;
    }
    
    .management-section h3 {
        font-size: 18px;
        margin-bottom: 8px;
    }
    
    .management-section p {
        font-size: 12px;
        margin-bottom: 12px;
    }
    
    .management-btn {
        padding: 10px 18px;
        font-size: 12px;
    }
}

@media (max-width: 576px) {
    .dashboard-container {
        padding: 6px;
    }
    
    .dashboard-header {
        margin-bottom: 8px;
    }
    
    .dashboard-title {
        font-size: 20px;
        margin-bottom: 2px;
    }
    
    .dashboard-subtitle {
        font-size: 11px;
    }
    
    .kpi-grid {
        grid-template-columns: 1fr 1fr;
        gap: 6px;
        margin-bottom: 8px;
    }
    
    .kpi-card {
        padding: 10px;
    }
    
    .kpi-icon {
        font-size: 18px;
        margin-bottom: 4px;
    }
    
    .kpi-value {
        font-size: 16px;
    }
    
    .kpi-label {
        font-size: 9px;
    }
    
    .welcome-content {
        padding: 25px 16px;
    }
    
    .sidebar-chart .chart-canvas,
    .half-width-chart .chart-canvas {
        height: 160px;
    }
    
    .sidebar-chart, .half-width-chart, .management-section {
        padding: 10px;
    }
    
    .sidebar-chart .chart-title,
    .half-width-chart .chart-title {
        font-size: 13px;
        margin-bottom: 6px;
    }
    
    .management-section h3 {
        font-size: 16px;
        margin-bottom: 6px;
    }
    
    .management-section p {
        font-size: 11px;
        margin-bottom: 10px;
    }
    
    .management-btn {
        padding: 8px 16px;
        font-size: 11px;
    }
}
</style>

<!-- Welcome Popup -->
<div id="welcomePopup" class="welcome-popup">
    <div class="welcome-content">
        <i class="bi bi-check-circle-fill" style="font-size: 48px; color: var(--blulinc-blue); margin-bottom: 16px;"></i>
        <h2 class="welcome-title">Welcome!</h2>
        <p class="welcome-message">
                               @if($isSuperAdmin)
                       Access the complete control panel of the Blulinc platform
                   @elseif($isPartnerAdmin) 
                       Manage your partner data in the Blulinc platform
                   @else
                       Welcome to the Blulinc platform
                   @endif
        </p>
        <button class="welcome-btn" onclick="closeWelcomePopup()">
            <i class="bi bi-arrow-right me-2"></i>Continue to Dashboard
        </button>
    </div>
</div>

<div class="dashboard-container">
    <!-- Dashboard Header -->
    <div class="dashboard-header">
        <h1 class="dashboard-title">
            <i class="bi bi-speedometer2 me-3"></i>
            @if($isSuperAdmin)
                Global Dashboard
            @elseif($isPartnerAdmin)
                Partner Dashboard
            @else
                Dashboard
            @endif
        </h1>
        <p class="dashboard-subtitle">Real-time control panel and analytics</p>
    </div>

    <!-- Main Grid Layout -->
    <div class="main-grid">
        <!-- Left Side: KPI Cards -->
        <div class="kpi-section">
            <div class="kpi-grid">
                <div class="kpi-card">
                    <div class="kpi-icon">
                        <i class="bi bi-people-fill"></i>
                    </div>
                    <div class="kpi-value" id="totalUsersKpi">{{ number_format($dashboardData['kpis']['totalUsers'] ?? 0) }}</div>
                    <div class="kpi-label">Total Users</div>
                </div>

                @if($isSuperAdmin || $isPartnerAdmin)
                <div class="kpi-card">
                    <div class="kpi-icon">
                        <i class="bi bi-person-check-fill"></i>
                    </div>
                    <div class="kpi-value" id="ampecoUsersKpi">{{ number_format($dashboardData['kpis']['totalAmpecoUsers'] ?? 0) }}</div>
                    <div class="kpi-label">Blulinc Users</div>
                </div>
                @endif

                <div class="kpi-card">
                    <div class="kpi-icon">
                        <i class="bi bi-lightning-charge-fill"></i>
                    </div>
                    <div class="kpi-value" id="energyKpi">{{ number_format($dashboardData['kpis']['totalEnergy'] ?? 0, 2) }}</div>
                    <div class="kpi-label">Total Energy (kWh)</div>
                </div>

                <div class="kpi-card">
                    <div class="kpi-icon">
                        <i class="bi bi-currency-euro"></i>
                    </div>
                    <div class="kpi-value" id="revenueKpi">€{{ number_format($dashboardData['kpis']['totalRevenue'] ?? 0, 2) }}</div>
                    <div class="kpi-label">Total Revenue</div>
                </div>

                @if($isSuperAdmin)
                <div class="kpi-card">
                    <div class="kpi-icon">
                        <i class="bi bi-building"></i>
                    </div>
                    <div class="kpi-value" id="partnersKpi">{{ number_format($dashboardData['kpis']['totalPartners'] ?? 0) }}</div>
                    <div class="kpi-label">Partners</div>
                </div>
                @endif

                @if($isSuperAdmin || $isPartnerAdmin)
                <div class="kpi-card">
                    <div class="kpi-icon">
                        <i class="bi bi-ev-station-fill"></i>
                    </div>
                    <div class="kpi-value" id="chargePointsKpi">{{ number_format($dashboardData['kpis']['totalChargePoints'] ?? 0) }}</div>
                    <div class="kpi-label">Charge Points</div>
                </div>

                <div class="kpi-card">
                    <div class="kpi-icon">
                        <i class="bi bi-geo-alt-fill"></i>
                    </div>
                    <div class="kpi-value" id="locationsKpi">{{ number_format($dashboardData['kpis']['totalLocations'] ?? 0) }}</div>
                    <div class="kpi-label">Locations</div>
                </div>
                @endif
            </div>
        </div>

        <!-- Right Side: Energy Distribution Chart -->
        <div class="sidebar-chart">
            <h3 class="chart-title">Energy Distribution by Type</h3>
            <div class="chart-canvas">
                <canvas id="energyChart"></canvas>
            </div>
        </div>
    </div>

    <!-- Bottom Grid: Tendencias Mensuales y Gestión de Usuarios lado a lado -->
    <div class="bottom-grid">
        <!-- Left: Monthly Trends Chart -->
        <div class="half-width-chart">
            <h3 class="chart-title">Monthly Trends</h3>
            <div class="chart-canvas">
                <canvas id="trendsChart"></canvas>
            </div>
        </div>

        <!-- Right: User Management Section -->
        <div class="management-section">
            <h3>
                <i class="bi bi-people me-2"></i>User Management
            </h3>
            <p>
                Access and manage all system users
            </p>
            <a href="{{ route('users.index') }}" class="management-btn">
                <i class="bi bi-arrow-right-circle"></i>
                Go to User List
            </a>
        </div>
    </div>
</div>

<!-- Chart.js CDN -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<script>
// Data from Laravel
const dashboardData = @json($dashboardData);
const isSuperAdmin = @json($isSuperAdmin);
const isPartnerAdmin = @json($isPartnerAdmin);

// Welcome popup functionality
function closeWelcomePopup() {
    const popup = document.getElementById('welcomePopup');
    popup.classList.add('hide');
    setTimeout(() => {
        popup.style.display = 'none';
    }, 500);
}

// Auto close popup after 5 seconds
setTimeout(() => {
    closeWelcomePopup();
}, 5000);

// Animate KPI numbers
function animateNumbers() {
    const kpiElements = [
        { id: 'totalUsersKpi', value: dashboardData.kpis?.totalUsers || 0 },
        { id: 'ampecoUsersKpi', value: dashboardData.kpis?.totalAmpecoUsers || 0 },
        { id: 'energyKpi', value: dashboardData.kpis?.totalEnergy || 0 },
        { id: 'revenueKpi', value: dashboardData.kpis?.totalRevenue || 0, prefix: '€' },
        { id: 'partnersKpi', value: dashboardData.kpis?.totalPartners || 0 },
        { id: 'chargePointsKpi', value: dashboardData.kpis?.totalChargePoints || 0 },
        { id: 'locationsKpi', value: dashboardData.kpis?.totalLocations || 0 }
    ];

    kpiElements.forEach(item => {
        const element = document.getElementById(item.id);
        if (element) {
            animateValue(element, 0, item.value, 2000, item.prefix);
        }
    });
}

function animateValue(element, start, end, duration, prefix = '') {
    const startTimestamp = performance.now();
    
    function step(timestamp) {
        const elapsed = timestamp - startTimestamp;
        const progress = Math.min(elapsed / duration, 1);
        
        const current = Math.floor(progress * (end - start) + start);
        const formatted = prefix + new Intl.NumberFormat().format(current);
        element.textContent = formatted;
        
        if (progress < 1) {
            requestAnimationFrame(step);
        }
    }
    
    requestAnimationFrame(step);
}

// Initialize charts after popup closes
setTimeout(() => {
    initializeCharts();
    animateNumbers();
}, 1500);

function initializeCharts() {
    // Energy Distribution Chart (Doughnut)
    const energyCtx = document.getElementById('energyChart').getContext('2d');
    new Chart(energyCtx, {
        type: 'doughnut',
        data: {
            labels: ['Personal Home', 'Semi-Public', 'Public Roaming', 'International Roaming'],
            datasets: [{
                data: [
                    dashboardData.energyByType?.personal || 0,
                    dashboardData.energyByType?.semipublic || 0,
                    dashboardData.energyByType?.public || 0,
                    dashboardData.energyByType?.roaming || 0
                ],
                backgroundColor: ['#015cff', '#87ceeb', '#4CAF50', '#FF9800'],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        padding: 15,
                        usePointStyle: true,
                        font: {
                            size: 12
                        }
                    }
                }
            },
            animation: {
                animateRotate: true,
                duration: 2000
            }
        }
    });

    // Monthly Trends Chart (Line)
    if (dashboardData.monthlyData && dashboardData.monthlyData.length > 0) {
        const trendsCtx = document.getElementById('trendsChart').getContext('2d');
        new Chart(trendsCtx, {
            type: 'line',
            data: {
                labels: dashboardData.monthlyData.map(item => item.month),
                datasets: [{
                    label: 'Users',
                    data: dashboardData.monthlyData.map(item => item.users),
                    borderColor: '#015cff',
                    backgroundColor: 'rgba(1, 92, 255, 0.1)',
                    fill: true,
                    tension: 0.4
                }, {
                    label: 'Energy (kWh)',
                    data: dashboardData.monthlyData.map(item => item.energy),
                    borderColor: '#4CAF50',
                    backgroundColor: 'rgba(76, 175, 80, 0.1)',
                    fill: true,
                    tension: 0.4,
                    yAxisID: 'y1'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'top'
                    }
                },
                scales: {
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                    },
                    y1: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        grid: {
                            drawOnChartArea: false,
                        },
                    }
                },
                animation: {
                    duration: 2000,
                    easing: 'easeInOutQuart'
                }
            }
        });
    }
}
</script>
@endsection
