<?php
ob_start();
?>

<style>
    /* Dashboard Ultra Moderno - Padronizado com Cores do Tema */
    .dashboard-wrapper {
        padding: 0;
    }

    .dashboard-tabs {
        display: flex;
        gap: 0.75rem;
        margin-bottom: 2rem;
        border-bottom: 1px solid rgba(0, 17, 34, 0.1);
    }

    .dashboard-tabs .nav-link {
        border: none;
        color: #64748b;
        font-weight: 600;
        font-size: 0.95rem;
        padding: 0.75rem 1.25rem;
        border-radius: 12px 12px 0 0;
        background: rgba(0, 17, 34, 0.04);
        transition: all 0.3s ease;
    }

    .dashboard-tabs .nav-link:hover {
        color: var(--primary-color);
        background: rgba(0, 17, 34, 0.08);
    }

    .dashboard-tabs .nav-link.active {
        color: #fff;
        background: var(--primary-color);
        box-shadow: 0 8px 24px rgba(0, 17, 34, 0.25);
    }

    /* Header com Gradiente e Glassmorphism - Padronizado */
    .dashboard-header {
        background: var(--primary-color);
        color: white;
        padding: 2.5rem;
        border-radius: 16px;
        margin-bottom: 2rem;
        box-shadow: 0 20px 60px rgba(0, 17, 34, 0.3);
        position: relative;
        overflow: hidden;
    }

    .dashboard-header::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -10%;
        width: 400px;
        height: 400px;
        background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
        border-radius: 50%;
        animation: float 6s ease-in-out infinite;
    }

    .dashboard-header::after {
        content: '';
        position: absolute;
        bottom: -30%;
        left: -5%;
        width: 300px;
        height: 300px;
        background: radial-gradient(circle, rgba(255, 255, 255, 0.08) 0%, transparent 70%);
        border-radius: 50%;
        animation: float 8s ease-in-out infinite reverse;
    }

    @keyframes float {

        0%,
        100% {
            transform: translateY(0px);
        }

        50% {
            transform: translateY(-20px);
        }
    }

    .dashboard-header-content {
        position: relative;
        z-index: 1;
    }

    .dashboard-header h1 {
        font-size: 2.25rem;
        font-weight: 700;
        margin: 0 0 0.5rem 0;
        text-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .dashboard-header p {
        margin: 0;
        opacity: 0.95;
        font-size: 1.05rem;
    }

    /* Cards de Estatísticas com Sparklines */
    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .stat-card {
        background: white;
        border-radius: 16px;
        padding: 1.75rem;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        position: relative;
        overflow: hidden;
        cursor: pointer;
    }

    .stat-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, var(--card-color-1), var(--card-color-2));
        transform: scaleX(0);
        transform-origin: left;
        transition: transform 0.4s ease;
    }

    .stat-card:hover::before {
        transform: scaleX(1);
    }

    .stat-card:hover {
        transform: translateY(-8px) scale(1.02);
        box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
    }

    .stat-card-vendas {
        --card-color-1: var(--primary-color);
        --card-color-2: var(--primary-color);
    }

    .stat-card-compras {
        --card-color-1: #11998e;
        --card-color-2: #38ef7d;
    }

    .stat-card-receber {
        --card-color-1: #10b981;
        --card-color-2: #059669;
    }

    .stat-card-pagar {
        --card-color-1: #ef4444;
        --card-color-2: #dc2626;
    }

    .stat-card-estoque {
        --card-color-1: #3a7bd5;
        --card-color-2: #00d2ff;
    }

    .stat-card-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 1.5rem;
    }

    .stat-icon {
        width: 56px;
        height: 56px;
        border-radius: 14px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.75rem;
        color: white;
        box-shadow: 0 8px 16px rgba(0, 0, 0, 0.15);
        transition: all 0.3s ease;
    }

    .stat-card:hover .stat-icon {
        transform: rotate(5deg) scale(1.1);
    }

    .stat-icon-vendas {
        background: var(--primary-color);
    }

    .stat-icon-compras {
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    }

    .stat-icon-receber {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    }

    .stat-icon-pagar {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    }

    .stat-icon-estoque {
        background: linear-gradient(135deg, #3a7bd5 0%, #00d2ff 100%);
    }

    .stat-sparkline {
        width: 80px;
        height: 40px;
    }

    .stat-label {
        font-size: 0.875rem;
        color: #8898aa;
        font-weight: 600;
        margin-bottom: 0.5rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .stat-value {
        font-size: 2rem;
        font-weight: 800;
        background: linear-gradient(135deg, var(--card-color-1), var(--card-color-2));
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        margin-bottom: 0.75rem;
        line-height: 1;
    }

    .stat-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 1rem;
        border-top: 1px solid #f8f9fa;
    }

    .stat-growth {
        font-size: 0.875rem;
        font-weight: 600;
        display: flex;
        align-items: center;
        gap: 0.4rem;
    }

    .stat-growth.positive {
        color: #10b981;
    }

    .stat-growth.negative {
        color: #ef4444;
    }

    .stat-meta {
        font-size: 0.75rem;
        color: #8898aa;
    }

    /* Grid de Gráficos com Glassmorphism */
    .charts-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .chart-card {
        background: white;
        border-radius: 16px;
        padding: 2rem;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }

    .chart-card-full {
        grid-column: 1 / -1;
    }

    .chart-card canvas {
        max-height: 280px !important;
        height: 280px !important;
    }

    .chart-card::before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        width: 200px;
        height: 200px;
        background: radial-gradient(circle, rgba(0, 17, 34, 0.05) 0%, transparent 70%);
        border-radius: 50%;
        transform: translate(30%, -30%);
    }

    .chart-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
    }

    .chart-card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1.5rem;
        position: relative;
        z-index: 1;
    }

    .chart-title {
        font-size: 1.25rem;
        font-weight: 700;
        color: #1e293b;
        margin: 0 0 0.25rem 0;
    }

    .chart-subtitle {
        font-size: 0.875rem;
        color: #64748b;
        margin: 0;
    }

    .chart-badge {
        background: var(--primary-color);
        color: white;
        padding: 0.5rem 1rem;
        border-radius: 12px;
        font-size: 0.875rem;
        font-weight: 600;
        box-shadow: 0 4px 12px rgba(0, 17, 34, 0.3);
    }

    /* Atividades com Timeline */
    .activity-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(360px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .activity-card {
        background: white;
        border-radius: 16px;
        padding: 2rem;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
        transition: all 0.3s ease;
    }

    .activity-card:hover {
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
    }

    .activity-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1.5rem;
        padding-bottom: 1rem;
        border-bottom: 2px solid #f1f5f9;
    }

    .activity-title {
        font-size: 1.25rem;
        font-weight: 700;
        color: #1e293b;
        margin: 0;
    }

    .activity-list {
        list-style: none;
        padding: 0;
        margin: 0;
        position: relative;
    }

    .activity-list::before {
        content: '';
        position: absolute;
        left: 20px;
        top: 0;
        bottom: 0;
        width: 2px;
        background: var(--primary-color);
        opacity: 0.2;
    }

    .activity-item {
        padding: 1rem 1rem 1rem 3rem;
        position: relative;
        transition: all 0.3s ease;
    }

    .activity-item::before {
        content: '';
        position: absolute;
        left: 14px;
        top: 1.5rem;
        width: 14px;
        height: 14px;
        background: white;
        border: 3px solid var(--primary-color);
        border-radius: 50%;
        box-shadow: 0 0 0 4px rgba(0, 17, 34, 0.1);
        transition: all 0.3s ease;
    }

    .activity-item:hover {
        background: linear-gradient(90deg, rgba(0, 17, 34, 0.03) 0%, transparent 100%);
    }

    .activity-item:hover::before {
        transform: scale(1.3);
        box-shadow: 0 0 0 6px rgba(0, 17, 34, 0.2);
    }

    .activity-item-title {
        font-weight: 700;
        color: #1e293b;
        margin-bottom: 0.35rem;
        font-size: 0.95rem;
    }

    .activity-item-meta {
        font-size: 0.825rem;
        color: #64748b;
        margin-bottom: 0.25rem;
    }

    .activity-item-value {
        font-weight: 800;
        font-size: 1.1rem;
        background: var(--primary-color);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }

    /* Badge de Status Modernizado */
    .status-badge {
        display: inline-block;
        padding: 0.3rem 0.85rem;
        border-radius: 20px;
        font-size: 0.7rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .badge-pendente {
        background: linear-gradient(135deg, #fbbf24 0%, #f59e0b 100%);
        color: white;
    }

    .badge-pago {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: white;
    }

    .badge-vencido {
        background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        color: white;
    }

    .badge-orcamento {
        background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
        color: white;
    }

    .badge-finalizado {
        background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        color: white;
    }

    .badge-cancelado {
        background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
        color: white;
    }

    /* Widget de Alerta */
    .alert-widget {
        background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
        border-left: 4px solid #f59e0b;
        padding: 1.25rem;
        border-radius: 12px;
        margin-bottom: 2rem;
        box-shadow: 0 4px 12px rgba(245, 158, 11, 0.2);
    }

    .alert-widget-title {
        font-weight: 700;
        color: #92400e;
        margin-bottom: 0.5rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .alert-widget-text {
        color: #78350f;
        font-size: 0.95rem;
    }

    /* Responsividade Aprimorada */
    @media (max-width: 1400px) {
        .charts-grid {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    @media (max-width: 992px) {
        .charts-grid {
            grid-template-columns: 1fr;
        }

        .activity-grid {
            grid-template-columns: 1fr;
        }
    }

    @media (max-width: 768px) {
        .stats-grid {
            grid-template-columns: 1fr;
        }

        .dashboard-header h1 {
            font-size: 1.75rem;
        }
    }

    /* Animações Avançadas */
    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(30px);
        }

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

    @keyframes scaleIn {
        from {
            opacity: 0;
            transform: scale(0.9);
        }

        to {
            opacity: 1;
            transform: scale(1);
        }
    }

    @keyframes slideInRight {
        from {
            opacity: 0;
            transform: translateX(30px);
        }

        to {
            opacity: 1;
            transform: translateX(0);
        }
    }

    .dashboard-header {
        animation: scaleIn 0.6s cubic-bezier(0.4, 0, 0.2, 1);
    }

    .stat-card {
        animation: fadeInUp 0.6s cubic-bezier(0.4, 0, 0.2, 1) backwards;
    }

    .stat-card:nth-child(1) {
        animation-delay: 0.1s;
    }

    .stat-card:nth-child(2) {
        animation-delay: 0.2s;
    }

    .stat-card:nth-child(3) {
        animation-delay: 0.3s;
    }

    .stat-card:nth-child(4) {
        animation-delay: 0.4s;
    }

    .chart-card {
        animation: fadeInUp 0.6s cubic-bezier(0.4, 0, 0.2, 1) backwards;
    }

    .chart-card:nth-child(1) {
        animation-delay: 0.5s;
    }

    .chart-card:nth-child(2) {
        animation-delay: 0.6s;
    }

    .chart-card:nth-child(3) {
        animation-delay: 0.7s;
    }

    .chart-card:nth-child(4) {
        animation-delay: 0.8s;
    }

    .activity-card {
        animation: slideInRight 0.6s cubic-bezier(0.4, 0, 0.2, 1) backwards;
    }

    .activity-card:nth-child(1) {
        animation-delay: 0.9s;
    }

    .activity-card:nth-child(2) {
        animation-delay: 1s;
    }

    /* Progress Rings */
    .progress-ring-container {
        position: relative;
        width: 60px;
        height: 60px;
    }

    .progress-ring-circle {
        transform: rotate(-90deg);
        transform-origin: 50% 50%;
    }

    .progress-ring-text {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 0.75rem;
        font-weight: 700;
        color: #1e293b;
    }
</style>

<div class="dashboard-wrapper">
    <!-- Header com Boas-vindas Animado -->
    <div class="dashboard-header">
        <div class="dashboard-header-content">
            <h1>
                <i class="bi bi-lightning-charge-fill me-2"></i>
                Olá, <?= htmlspecialchars($user['name'] ?? 'Usuário') ?>!
            </h1>
            <p>
                <i class="bi bi-calendar-event me-2"></i>
                Visão geral das operações em <?php
                $meses = [
                    'Janeiro',
                    'Fevereiro',
                    'Março',
                    'Abril',
                    'Maio',
                    'Junho',
                    'Julho',
                    'Agosto',
                    'Setembro',
                    'Outubro',
                    'Novembro',
                    'Dezembro'
                ];
                echo $meses[(int) date('m') - 1] . ' de ' . date('Y');
                ?>
            </p>
        </div>
    </div>
    <div class="dashboard-tabs" id="dashboardTabs" role="tablist">
        <button type="button" class="nav-link active" data-dashboard-tab="vendas">
            <i class="bi bi-bar-chart-line me-2"></i>
            Vendas
        </button>
        <button type="button" class="nav-link" data-dashboard-tab="compras">
            <i class="bi bi-cart4 me-2"></i>
            Compras
        </button>
        <button type="button" class="nav-link" data-dashboard-tab="estoque">
            <i class="bi bi-box-seam me-2"></i>
            Estoque
        </button>
        <button type="button" class="nav-link" data-dashboard-tab="financeiro">
            <i class="bi bi-cash-coin me-2"></i>
            Financeiro
        </button>
    </div>

    <!-- Cards de Estatísticas com Sparklines -->
    <div class="stats-grid" data-dashboard-section="stats">
        <!-- Vendas do Mês -->
        <div class="stat-card stat-card-vendas" data-dashboard-area="vendas"
            onclick="window.location.href=appUrl('/vendas')">
            <div class="stat-card-header">
                <div class="stat-icon stat-icon-vendas">
                    <i class="bi bi-graph-up-arrow"></i>
                </div>
                <canvas id="sparklineVendas" class="stat-sparkline" width="80" height="40"></canvas>
            </div>
            <div class="stat-label">Vendas do Mês</div>
            <div class="stat-value"><?= formatCurrency($stats['sales_total'] ?? 0) ?></div>
            <div class="stat-footer">
                <div class="stat-growth <?= ($stats['sales_growth'] ?? 0) >= 0 ? 'positive' : 'negative' ?>">
                    <i class="bi bi-<?= ($stats['sales_growth'] ?? 0) >= 0 ? 'trending-up' : 'trending-down' ?>"></i>
                    <?= abs($stats['sales_growth'] ?? 0) ?>%
                </div>
                <div class="stat-meta">vs mês anterior</div>
            </div>
        </div>

        <!-- Compras do Mês -->
        <div class="stat-card stat-card-compras" data-dashboard-area="compras"
            onclick="window.location.href=appUrl('/compras')">
            <div class="stat-card-header">
                <div class="stat-icon stat-icon-compras">
                    <i class="bi bi-cart-check-fill"></i>
                </div>
                <canvas id="sparklineCompras" class="stat-sparkline" width="80" height="40"></canvas>
            </div>
            <div class="stat-label">Compras do Mês</div>
            <div class="stat-value"><?= formatCurrency($stats['purchases_total'] ?? 0) ?></div>
            <div class="stat-footer">
                <div class="stat-growth">
                    <i class="bi bi-shop"></i>
                    Fornecedores
                </div>
                <div class="stat-meta">ativos</div>
            </div>
        </div>

        <!-- Estoque Atual -->
        <div class="stat-card stat-card-estoque" data-dashboard-area="estoque"
            onclick="window.location.href=appUrl('/gestor-estoque')">
            <div class="stat-card-header">
                <div class="stat-icon stat-icon-estoque">
                    <i class="bi bi-boxes"></i>
                </div>
                <canvas id="sparklineEstoque" class="stat-sparkline" width="80" height="40"></canvas>
            </div>
            <div class="stat-label">Itens em Estoque</div>
            <div class="stat-value"><?= number_format((float) ($stats['inventory_total'] ?? 0), 0, ',', '.') ?></div>
            <div class="stat-footer">
                <div class="stat-growth">
                    <i class="bi bi-building"></i>
                    <?= $stats['inventory_categories'] ?? 0 ?> categorias
                </div>
                <div class="stat-meta">ativos</div>
            </div>
        </div>

        <!-- Contas a Receber -->
        <div class="stat-card stat-card-receber" data-dashboard-area="financeiro"
            onclick="window.location.href=appUrl('/entradas')">
            <div class="stat-card-header">
                <div class="stat-icon stat-icon-receber">
                    <i class="bi bi-wallet2"></i>
                </div>
                <div class="progress-ring-container">
                    <svg class="progress-ring-circle" width="60" height="60">
                        <circle cx="30" cy="30" r="24" stroke="#f093fb" stroke-width="4" fill="none" opacity="0.1" />
                        <circle id="progressReceber" cx="30" cy="30" r="24" stroke="#f093fb" stroke-width="4"
                            fill="none" stroke-dasharray="150.8" stroke-dashoffset="0"
                            style="transition: stroke-dashoffset 1s ease;" />
                    </svg>
                    <div class="progress-ring-text"><?= $stats['receivables_count'] ?? 0 ?></div>
                </div>
            </div>
            <div class="stat-label">Contas a Receber</div>
            <div class="stat-value"><?= formatCurrency($stats['receivables_total'] ?? 0) ?></div>
            <div class="stat-footer">
                <div class="stat-growth">
                    <i class="bi bi-file-earmark-text-fill"></i>
                    <?= $stats['receivables_count'] ?? 0 ?> títulos
                </div>
                <div class="stat-meta">em aberto</div>
            </div>
        </div>

        <!-- Contas a Pagar -->
        <div class="stat-card stat-card-pagar" data-dashboard-area="financeiro"
            onclick="window.location.href=appUrl('/saidas')">
            <div class="stat-card-header">
                <div class="stat-icon stat-icon-pagar">
                    <i class="bi bi-credit-card-fill"></i>
                </div>
                <div class="progress-ring-container">
                    <svg class="progress-ring-circle" width="60" height="60">
                        <circle cx="30" cy="30" r="24" stroke="#fa709a" stroke-width="4" fill="none" opacity="0.1" />
                        <circle id="progressPagar" cx="30" cy="30" r="24" stroke="#fa709a" stroke-width="4" fill="none"
                            stroke-dasharray="150.8" stroke-dashoffset="0"
                            style="transition: stroke-dashoffset 1s ease;" />
                    </svg>
                    <div class="progress-ring-text"><?= $stats['payables_count'] ?? 0 ?></div>
                </div>
            </div>
            <div class="stat-label">Contas a Pagar</div>
            <div class="stat-value"><?= formatCurrency($stats['payables_total'] ?? 0) ?></div>
            <div class="stat-footer">
                <div class="stat-growth">
                    <i class="bi bi-file-earmark-text-fill"></i>
                    <?= $stats['payables_count'] ?? 0 ?> títulos
                </div>
                <div class="stat-meta">em aberto</div>
            </div>
        </div>
    </div>

    <!-- Gráficos Interativos -->
    <div class="charts-grid" data-dashboard-section="charts">
        <!-- Evolução de Vendas (Área) -->
        <div class="chart-card" data-dashboard-area="vendas">
            <div class="chart-card-header">
                <div>
                    <h3 class="chart-title">📈 Evolução de Vendas</h3>
                    <p class="chart-subtitle">Últimos 30 dias • Tendência de crescimento</p>
                </div>
            </div>
            <div style="position: relative; height: 280px;">
                <canvas id="chartVendasTempo"></canvas>
            </div>
        </div>

        <!-- Evolução de Compras (Área) -->
        <div class="chart-card" data-dashboard-area="compras">
            <div class="chart-card-header">
                <div>
                    <h3 class="chart-title">🛒 Evolução de Compras</h3>
                    <p class="chart-subtitle">Últimos 30 dias • Volume adquirido</p>
                </div>
            </div>
            <div style="position: relative; height: 280px;">
                <canvas id="chartComprasTempo"></canvas>
            </div>
        </div>

        <!-- Contas a Receber (Rosca) -->
        <div class="chart-card" data-dashboard-area="financeiro">
            <div class="chart-card-header">
                <div>
                    <h3 class="chart-title">💰 Contas a Receber</h3>
                    <p class="chart-subtitle">Distribuição por vencimento</p>
                </div>
                <div class="chart-badge"><?= formatCurrency($stats['receivables_total'] ?? 0) ?></div>
            </div>
            <div style="position: relative; height: 280px;">
                <canvas id="chartContasReceber"></canvas>
            </div>
        </div>

        <!-- Top Produtos (Barras Horizontais) -->
        <div class="chart-card" data-dashboard-area="estoque">
            <div class="chart-card-header">
                <div>
                    <h3 class="chart-title">🏆 Top 5 Produtos</h3>
                    <p class="chart-subtitle">Mais vendidos no mês atual</p>
                </div>
            </div>
            <div style="position: relative; height: 280px;">
                <canvas id="chartTopProdutos"></canvas>
            </div>
        </div>

        <!-- Contas a Pagar (Rosca) -->
        <div class="chart-card" data-dashboard-area="financeiro">
            <div class="chart-card-header">
                <div>
                    <h3 class="chart-title">💳 Contas a Pagar</h3>
                    <p class="chart-subtitle">Distribuição por vencimento</p>
                </div>
                <div class="chart-badge"><?= formatCurrency($stats['payables_total'] ?? 0) ?></div>
            </div>
            <div style="position: relative; height: 280px;">
                <canvas id="chartContasPagar"></canvas>
            </div>
        </div>

        <!-- Comparativo Financeiro (Linha em Ondas) -->
        <div class="chart-card chart-card-full" data-dashboard-area="financeiro">
            <div class="chart-card-header">
                <div>
                    <h3 class="chart-title">🌊 Fluxo Financeiro</h3>
                    <p class="chart-subtitle">Comparativo mensal entre contas a pagar e a receber</p>
                </div>
            </div>
            <div style="position: relative; height: 320px;">
                <canvas id="chartFinanceComparativo"></canvas>
            </div>
        </div>
    </div>

    <!-- Timeline de Atividades -->
    <div class="activity-grid" data-dashboard-section="activity">
        <!-- Vendas Recentes -->
        <div class="activity-card" data-dashboard-area="vendas">
            <div class="activity-header">
                <h3 class="activity-title">
                    <i class="bi bi-clock-history me-2" style="color: var(--primary-color);"></i>
                    Vendas Recentes
                </h3>
                <a href="<?= url('/vendas') ?>" class="btn btn-sm btn-primary">
                    <i class="bi bi-arrow-right me-1"></i> Ver todas
                </a>
            </div>
            <ul class="activity-list">
                <?php if (!empty($vendas_recentes) && count($vendas_recentes) > 0): ?>
                    <?php foreach (array_slice($vendas_recentes, 0, 6) as $venda): ?>
                        <li class="activity-item">
                            <div class="d-flex justify-content-between align-items-start">
                                <div class="flex-grow-1">
                                    <div class="activity-item-title">
                                        <?= htmlspecialchars($venda['sale_number'] ?? $venda['numero'] ?? 'N/A') ?>
                                        <span class="status-badge badge-<?= strtolower($venda['status']) ?>">
                                            <?= ucfirst($venda['status']) ?>
                                        </span>
                                    </div>
                                    <div class="activity-item-meta">
                                        <i class="bi bi-person-circle me-1"></i>
                                        <?= htmlspecialchars($venda['customer_name'] ?? $venda['cliente_name'] ?? 'Cliente') ?>
                                    </div>
                                    <div class="activity-item-meta">
                                        <i class="bi bi-calendar3 me-1"></i>
                                        <?= date('d/m/Y H:i', strtotime($venda['sale_date'] ?? $venda['created_at'])) ?>
                                    </div>
                                </div>
                                <div class="activity-item-value">
                                    <?= formatCurrency($venda['total'] ?? 0) ?>
                                </div>
                            </div>
                        </li>
                    <?php endforeach; ?>
                <?php else: ?>
                    <li class="activity-item" style="border: none;">
                        <div class="text-center text-muted py-4">
                            <i class="bi bi-inbox" style="font-size: 3rem; opacity: 0.3;"></i>
                            <p class="mb-0 mt-3">Nenhuma venda registrada ainda</p>
                            <a href="<?= url('/vendas/criar') ?>" class="btn btn-sm btn-primary mt-2">
                                <i class="bi bi-plus-circle me-1"></i> Nova Venda
                            </a>
                        </div>
                    </li>
                <?php endif; ?>
            </ul>
        </div>

    </div>
</div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
    // Tabs dinâmicas do dashboard
    const dashboardTabs = document.querySelectorAll('[data-dashboard-tab]');
    const dashboardAreas = document.querySelectorAll('[data-dashboard-area]');
    const dashboardSections = document.querySelectorAll('[data-dashboard-section]');

    function updateDashboardArea(area) {
        dashboardAreas.forEach((element) => {
            const shouldShow = element.dataset.dashboardArea === area;
            element.classList.toggle('d-none', !shouldShow);
        });

        dashboardSections.forEach((section) => {
            const hasVisibleChildren = Array.from(section.querySelectorAll('[data-dashboard-area]'))
                .some((child) => !child.classList.contains('d-none'));
            section.classList.toggle('d-none', !hasVisibleChildren);
        });
    }

    dashboardTabs.forEach((tab) => {
        tab.addEventListener('click', () => {
            if (tab.classList.contains('active')) {
                return;
            }

            dashboardTabs.forEach((btn) => btn.classList.remove('active'));
            tab.classList.add('active');
            updateDashboardArea(tab.dataset.dashboardTab);
        });
    });

    // Configurações globais do Chart.js
    Chart.defaults.font.family = "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif";
    Chart.defaults.color = '#64748b';
    Chart.defaults.plugins.legend.labels.usePointStyle = true;
    Chart.defaults.plugins.legend.labels.padding = 15;

    // Plugins e utilitários globais para gráficos modernizados
    const currencyFormatter = new Intl.NumberFormat('pt-BR', {
        style: 'currency',
        currency: 'BRL'
    });

    function formatCurrencyValue(value) {
        return currencyFormatter.format(Number(value || 0));
    }

    const doughnutShadowPlugin = {
        id: 'doughnutShadow',
        afterDatasetsDraw(chart, args, pluginOptions) {
            if (chart.config.type !== 'doughnut') {
                return;
            }

            const { ctx } = chart;
            ctx.save();
            ctx.shadowColor = 'rgba(15, 23, 42, 0.25)';
            ctx.shadowBlur = 18;
            ctx.shadowOffsetY = 8;

            chart.getDatasetMeta(0).data.forEach((arc) => {
                arc.draw(ctx);
            });

            ctx.restore();
        }
    };

    const centerTextPlugin = {
        id: 'centerText',
        afterDraw(chart, args, pluginOptions) {
            if (chart.config.type !== 'doughnut') {
                return;
            }

            const options = chart.config.options.plugins.centerText;
            if (!options || !options.display) {
                return;
            }

            const { ctx } = chart;
            const { left, right, top, bottom } = chart.chartArea;
            const centerX = (left + right) / 2;
            const centerY = (top + bottom) / 2;

            ctx.save();
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';

            if (options.title) {
                ctx.font = '600 12px "Segoe UI"';
                ctx.fillStyle = '#94a3b8';
                ctx.fillText(options.title.toUpperCase(), centerX, centerY - 32);
            }

            if (options.value) {
                ctx.font = '700 20px "Segoe UI"';
                ctx.fillStyle = '#0f172a';
                ctx.fillText(options.value, centerX, centerY - (options.subtitle ? 6 : 0));
            }

            if (options.subtitle) {
                ctx.font = '600 12px "Segoe UI"';
                ctx.fillStyle = '#94a3b8';
                ctx.fillText(options.subtitle, centerX, centerY + 18);
            }

            ctx.restore();
        }
    };

    Chart.register(doughnutShadowPlugin, centerTextPlugin);

    function createSegmentGradient(ctx, colorStops) {
        const gradient = ctx.createLinearGradient(0, 0, 180, 180);
        gradient.addColorStop(0, colorStops[0]);
        gradient.addColorStop(1, colorStops[1]);
        return gradient;
    }

    function buildFinanceDoughnut(config) {
        const canvas = document.getElementById(config.id);
        if (!canvas) {
            return null;
        }

        const ctx = canvas.getContext('2d');
        const rawData = (config.data || []).map((value) => Number(value || 0));
        const labels = config.labels || [];
        const total = rawData.reduce((sum, value) => sum + value, 0);
        const hasData = rawData.some((value) => value > 0);

        const palette = config.palette || [];
        const gradients = [];
        const datasetData = hasData ? rawData : [1];
        const datasetLabels = hasData ? labels : ['Sem dados'];

        datasetData.forEach((value, index) => {
            const colors = palette[index % palette.length] || ['rgba(148, 163, 184, 0.45)', 'rgba(148, 163, 184, 0.15)'];
            gradients.push(createSegmentGradient(ctx, colors));
        });

        return new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: datasetLabels,
                datasets: [{
                    data: datasetData,
                    backgroundColor: gradients,
                    borderWidth: 0,
                    hoverOffset: 18,
                    spacing: 6,
                    borderRadius: 18
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '72%',
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 18,
                            font: {
                                size: 13,
                                weight: '600'
                            },
                            color: '#475569'
                        }
                    },
                    tooltip: {
                        enabled: hasData,
                        backgroundColor: 'rgba(15, 23, 42, 0.92)',
                        padding: 14,
                        borderColor: config.tooltipBorder || '#334155',
                        borderWidth: 2,
                        displayColors: false,
                        callbacks: {
                            label: (context) => {
                                if (!hasData) {
                                    return 'Sem dados disponíveis';
                                }
                                const value = context.parsed;
                                const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : '0.0';
                                return `${context.label}: ${formatCurrencyValue(value)} (${percentage}%)`;
                            }
                        }
                    },
                    centerText: {
                        display: true,
                        title: config.centerTitle,
                        value: hasData ? formatCurrencyValue(total) : 'R$ 0,00',
                        subtitle: config.centerSubtitle
                    }
                }
            }
        });
    }

    // Criar gradientes para gráficos
    function createGradient(ctx, color1, color2) {
        const gradient = ctx.createLinearGradient(0, 0, 0, 400);
        gradient.addColorStop(0, color1);
        gradient.addColorStop(1, color2);
        return gradient;
    }

    // Sparkline de Vendas (mini gráfico no card)
    const ctxSparklineVendas = document.getElementById('sparklineVendas');
    if (ctxSparklineVendas) {
        const sparklineData = <?= json_encode(array_slice($vendas_ultimos_30_dias['data'] ?? [], -7)) ?>;
        new Chart(ctxSparklineVendas, {
            type: 'line',
            data: {
                labels: Array(sparklineData.length).fill(''),
                datasets: [{
                    data: sparklineData,
                    borderColor: 'var(--primary-color)',
                    backgroundColor: 'rgba(0, 17, 34, 0.2)',
                    tension: 0.4,
                    fill: true,
                    borderWidth: 2,
                    pointRadius: 0
                }]
            },
            options: {
                responsive: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: { display: false },
                    y: { display: false }
                }
            }
        });
    }

    // Sparkline de Compras
    const ctxSparklineCompras = document.getElementById('sparklineCompras');
    if (ctxSparklineCompras) {
        const comprasData = [0, 150, 300, 450, 380, 420, <?= $stats['purchases_total'] ?? 0 ?>]; // Dados simulados
        new Chart(ctxSparklineCompras, {
            type: 'line',
            data: {
                labels: Array(comprasData.length).fill(''),
                datasets: [{
                    data: comprasData,
                    borderColor: '#11998e',
                    backgroundColor: 'rgba(17, 153, 142, 0.2)',
                    tension: 0.4,
                    fill: true,
                    borderWidth: 2,
                    pointRadius: 0
                }]
            },
            options: {
                responsive: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: { display: false },
                    y: { display: false }
                }
            }
        });
    }

    // Sparkline de Estoque
    const ctxSparklineEstoque = document.getElementById('sparklineEstoque');
    if (ctxSparklineEstoque) {
        const estoqueData = <?= json_encode($estoque_sparkline ?? [0, 0, 0, 0, 0, 0, (float) ($stats['inventory_total'] ?? 0)]) ?>;
        new Chart(ctxSparklineEstoque, {
            type: 'line',
            data: {
                labels: Array(estoqueData.length).fill(''),
                datasets: [{
                    data: estoqueData,
                    borderColor: '#3a7bd5',
                    backgroundColor: 'rgba(58, 123, 213, 0.2)',
                    tension: 0.4,
                    fill: true,
                    borderWidth: 2,
                    pointRadius: 0
                }]
            },
            options: {
                responsive: false,
                plugins: { legend: { display: false } },
                scales: {
                    x: { display: false },
                    y: { display: false }
                }
            }
        });
    }

    // Evolução de Vendas (Gráfico de Área)
    const ctxVendasTempo = document.getElementById('chartVendasTempo');
    if (ctxVendasTempo) {
        const gradient = ctxVendasTempo.getContext('2d').createLinearGradient(0, 0, 0, 300);
        gradient.addColorStop(0, 'rgba(0, 17, 34, 0.4)');
        gradient.addColorStop(1, 'rgba(0, 17, 34, 0.05)');

        new Chart(ctxVendasTempo, {
            type: 'line',
            data: {
                labels: <?= json_encode($vendas_ultimos_30_dias['labels'] ?? []) ?>,
                datasets: [{
                    label: 'Vendas',
                    data: <?= json_encode($vendas_ultimos_30_dias['data'] ?? []) ?>,
                    borderColor: 'var(--primary-color)',
                    backgroundColor: gradient,
                    tension: 0.4,
                    fill: true,
                    borderWidth: 3,
                    pointBackgroundColor: 'var(--primary-color)',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    intersect: false,
                    mode: 'index'
                },
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(30, 41, 59, 0.95)',
                        padding: 12,
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: 'var(--primary-color)',
                        borderWidth: 2,
                        displayColors: false,
                        callbacks: {
                            label: function (context) {
                                return 'R$ ' + context.parsed.y.toLocaleString('pt-BR', { minimumFractionDigits: 2 });
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)',
                            drawBorder: false
                        },
                        ticks: {
                            callback: function (value) {
                                return 'R$ ' + value.toLocaleString('pt-BR');
                            }
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    }

    // Evolução de Compras (Gráfico de Área)
    const ctxComprasTempo = document.getElementById('chartComprasTempo');
    if (ctxComprasTempo) {
        const gradientCompras = ctxComprasTempo.getContext('2d').createLinearGradient(0, 0, 0, 300);
        gradientCompras.addColorStop(0, 'rgba(17, 153, 142, 0.35)');
        gradientCompras.addColorStop(1, 'rgba(56, 239, 125, 0.05)');

        new Chart(ctxComprasTempo, {
            type: 'line',
            data: {
                labels: <?= json_encode($compras_ultimos_30_dias['labels'] ?? []) ?>,
                datasets: [{
                    label: 'Compras',
                    data: <?= json_encode($compras_ultimos_30_dias['data'] ?? []) ?>,
                    borderColor: '#11998e',
                    backgroundColor: gradientCompras,
                    tension: 0.4,
                    fill: true,
                    borderWidth: 3,
                    pointBackgroundColor: '#11998e',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 2,
                    pointRadius: 4,
                    pointHoverRadius: 6
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    intersect: false,
                    mode: 'index'
                },
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(30, 41, 59, 0.95)',
                        padding: 12,
                        titleColor: '#fff',
                        bodyColor: '#fff',
                        borderColor: '#11998e',
                        borderWidth: 2,
                        displayColors: false,
                        callbacks: {
                            label: function (context) {
                                return 'R$ ' + context.parsed.y.toLocaleString('pt-BR', { minimumFractionDigits: 2 });
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)',
                            drawBorder: false
                        },
                        ticks: {
                            callback: function (value) {
                                return 'R$ ' + value.toLocaleString('pt-BR');
                            }
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    }

    // Top Produtos (Barras Horizontais com Gradiente)
    const ctxTopProdutos = document.getElementById('chartTopProdutos');
    if (ctxTopProdutos) {
        new Chart(ctxTopProdutos, {
            type: 'bar',
            data: {
                labels: <?= json_encode($top_produtos['labels'] ?? ['Sem dados']) ?>,
                datasets: [{
                    label: 'Quantidade Vendida',
                    data: <?= json_encode($top_produtos['data'] ?? [0]) ?>,
                    backgroundColor: [
                        'rgba(0, 17, 34, 0.8)',
                        'rgba(0, 82, 163, 0.8)',
                        'rgba(17, 153, 142, 0.8)',
                        'rgba(58, 123, 213, 0.8)',
                        'rgba(16, 185, 129, 0.8)'
                    ],
                    borderRadius: 8,
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                indexAxis: 'y',
                plugins: {
                    legend: { display: false },
                    tooltip: {
                        backgroundColor: 'rgba(30, 41, 59, 0.95)',
                        padding: 12,
                        borderColor: 'var(--primary-color)',
                        borderWidth: 2
                    }
                },
                scales: {
                    x: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    y: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    }

    // Comparativo Financeiro (Ondas)
    const financeComparison = <?= json_encode($finance_comparativo ?? ['labels' => [], 'receber' => [], 'pagar' => []]) ?>;
    const ctxFinanceComparativo = document.getElementById('chartFinanceComparativo');
    if (ctxFinanceComparativo) {
        const labels = (financeComparison.labels && financeComparison.labels.length) ? financeComparison.labels : ['Sem dados'];
        const receberData = (financeComparison.receber && financeComparison.receber.length) ? financeComparison.receber : [0];
        const pagarData = (financeComparison.pagar && financeComparison.pagar.length) ? financeComparison.pagar : [0];

        const context = ctxFinanceComparativo.getContext('2d');
        const gradientReceber = context.createLinearGradient(0, 0, 0, 320);
        gradientReceber.addColorStop(0, 'rgba(16, 185, 129, 0.35)');
        gradientReceber.addColorStop(1, 'rgba(16, 185, 129, 0.05)');

        const gradientPagar = context.createLinearGradient(0, 0, 0, 320);
        gradientPagar.addColorStop(0, 'rgba(248, 113, 113, 0.35)');
        gradientPagar.addColorStop(1, 'rgba(248, 113, 113, 0.05)');

        new Chart(ctxFinanceComparativo, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'A Receber',
                        data: receberData,
                        borderColor: '#10b981',
                        backgroundColor: gradientReceber,
                        tension: 0.45,
                        fill: true,
                        borderWidth: 3,
                        pointRadius: 0,
                        pointHoverRadius: 6,
                        pointBackgroundColor: '#10b981'
                    },
                    {
                        label: 'A Pagar',
                        data: pagarData,
                        borderColor: '#f87171',
                        backgroundColor: gradientPagar,
                        tension: 0.45,
                        fill: true,
                        borderWidth: 3,
                        pointRadius: 0,
                        pointHoverRadius: 6,
                        pointBackgroundColor: '#f87171'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false
                },
                plugins: {
                    legend: {
                        position: 'top',
                        labels: {
                            usePointStyle: true,
                            padding: 20
                        }
                    },
                    tooltip: {
                        backgroundColor: 'rgba(15, 23, 42, 0.92)',
                        padding: 14,
                        borderColor: '#1e293b',
                        borderWidth: 2,
                        callbacks: {
                            label: (context) => `${context.dataset.label}: ${formatCurrencyValue(context.parsed.y)}`
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(148, 163, 184, 0.15)',
                            drawBorder: false
                        },
                        ticks: {
                            callback: (value) => formatCurrencyValue(value)
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    }

    // Gráficos Financeiros Modernizados
    const financePalettes = {
        receber: [
            ['rgba(16, 185, 129, 1)', 'rgba(45, 212, 191, 0.35)'],
            ['rgba(59, 130, 246, 1)', 'rgba(79, 70, 229, 0.3)'],
            ['rgba(250, 204, 21, 1)', 'rgba(251, 191, 36, 0.35)'],
            ['rgba(236, 72, 153, 1)', 'rgba(249, 168, 212, 0.35)'],
            ['rgba(14, 116, 144, 1)', 'rgba(56, 189, 248, 0.35)']
        ],
        pagar: [
            ['rgba(248, 113, 113, 1)', 'rgba(239, 68, 68, 0.35)'],
            ['rgba(251, 146, 60, 1)', 'rgba(249, 115, 22, 0.35)'],
            ['rgba(14, 165, 233, 1)', 'rgba(56, 189, 248, 0.35)'],
            ['rgba(129, 140, 248, 1)', 'rgba(99, 102, 241, 0.35)'],
            ['rgba(74, 222, 128, 1)', 'rgba(34, 197, 94, 0.3)']
        ]
    };

    buildFinanceDoughnut({
        id: 'chartContasReceber',
        labels: <?= json_encode($contas_receber['labels'] ?? ['Sem dados']) ?>,
        data: <?= json_encode($contas_receber['data'] ?? [0]) ?>,
        palette: financePalettes.receber,
        centerTitle: 'A receber',
        centerSubtitle: 'em aberto',
        tooltipBorder: '#0ea5e9'
    });

    buildFinanceDoughnut({
        id: 'chartContasPagar',
        labels: <?= json_encode($contas_pagar['labels'] ?? ['Sem dados']) ?>,
        data: <?= json_encode($contas_pagar['data'] ?? [0]) ?>,
        palette: financePalettes.pagar,
        centerTitle: 'A pagar',
        centerSubtitle: 'pendentes',
        tooltipBorder: '#f97316'
    });

    // Animar Progress Rings
    setTimeout(() => {
        const receberCount = <?= $stats['receivables_count'] ?? 0 ?>;
        const receberMax = 20; // Máximo para cálculo
        const receberProgress = Math.min((receberCount / receberMax) * 100, 100);
        const receberOffset = 150.8 - (150.8 * receberProgress / 100);
        document.getElementById('progressReceber').style.strokeDashoffset = receberOffset;

        const pagarCount = <?= $stats['payables_count'] ?? 0 ?>;
        const pagarMax = 20;
        const pagarProgress = Math.min((pagarCount / pagarMax) * 100, 100);
        const pagarOffset = 150.8 - (150.8 * pagarProgress / 100);
        document.getElementById('progressPagar').style.strokeDashoffset = pagarOffset;
    }, 500);

    // Contador animado para valores
    function animateValue(id, start, end, duration) {
        const obj = document.getElementById(id);
        if (!obj) return;

        const range = end - start;
        const increment = range / (duration / 16);
        let current = start;

        const timer = setInterval(() => {
            current += increment;
            if ((increment > 0 && current >= end) || (increment < 0 && current <= end)) {
                current = end;
                clearInterval(timer);
            }
            obj.textContent = 'R$ ' + current.toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        }, 16);
    }

    // Exibe área inicial
    updateDashboardArea('vendas');
</script>

<?php
$content = ob_get_clean();
$activeMenu = 'dashboard';
include \ROOT_PATH . '/views/layouts/app.php';
?>