@extends('layouts.app')

@section('title', 'Dashboard - BC Sistema de Gestão Financeira')

@section('styles')
<style>
    :root {
        --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        --success-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        --warning-gradient: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        --danger-gradient: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
        --info-gradient: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
    }
    
    .dashboard-container {
        background: linear-gradient(120deg, #f8f9fa 0%, #e9ecef 100%);
        min-height: 100vh;
        padding: 2rem 0;
    }
    
    .executive-card {
        background: #fff;
        border: none;
        border-radius: 20px;
        box-shadow: 0 15px 35px rgba(0,0,0,0.08);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        position: relative;
        overflow: hidden;
    }
    
    .executive-card:hover {
        transform: translateY(-8px);
        box-shadow: 0 25px 50px rgba(0,0,0,0.15);
    }
    
    .executive-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 5px;
        background: var(--primary-gradient);
    }
    
    .metric-display {
        font-size: 3rem;
        font-weight: 800;
        line-height: 1;
        background: var(--primary-gradient);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }
    
    .professional-banner {
        background: var(--primary-gradient);
        border-radius: 25px;
        color: white;
        margin-bottom: 3rem;
        position: relative;
        overflow: hidden;
    }
    
    .professional-banner::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -50%;
        width: 100%;
        height: 200%;
        background: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.05'%3E%3Ccircle cx='30' cy='30' r='2'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
        animation: float 20s infinite linear;
    }
    
    @keyframes float {
        0% { transform: translate(-50%, -50%) rotate(0deg); }
        100% { transform: translate(-50%, -50%) rotate(360deg); }
    }
    
    .action-button {
        background: rgba(255,255,255,0.15);
        border: 2px solid rgba(255,255,255,0.2);
        color: white;
        border-radius: 15px;
        padding: 15px 25px;
        transition: all 0.3s ease;
        backdrop-filter: blur(10px);
        font-weight: 600;
    }
    
    .action-button:hover {
        background: rgba(255,255,255,0.25);
        color: white;
        transform: translateY(-3px) scale(1.02);
        box-shadow: 0 10px 25px rgba(0,0,0,0.2);
    }
    
    .financial-widget {
        background: #fff;
        border-radius: 20px;
        padding: 2rem;
        box-shadow: 0 10px 30px rgba(0,0,0,0.08);
        margin-bottom: 2rem;
        position: relative;
        overflow: hidden;
    }
    
    .financial-widget::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: var(--primary-gradient);
    }
    
    .widget-icon {
        width: 80px;
        height: 80px;
        border-radius: 20px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 2.5rem;
        margin-bottom: 1rem;
    }
    
    .status-badge {
        padding: 8px 16px;
        border-radius: 20px;
        font-weight: 600;
        font-size: 0.85rem;
    }
    
    .performance-indicator {
        background: var(--success-gradient);
        color: white;
        padding: 5px 12px;
        border-radius: 15px;
        font-size: 0.8rem;
        font-weight: 600;
    }
    
    .alert-professional {
        border: none;
        border-radius: 15px;
        border-left: 5px solid;
        background: rgba(255,255,255,0.9);
        backdrop-filter: blur(10px);
    }
    
    .chart-professional {
        background: #fff;
        border-radius: 20px;
        padding: 2rem;
        box-shadow: 0 10px 30px rgba(0,0,0,0.08);
        height: 400px;
    }
</style>
@endsection

@section('header')
<div class="professional-banner p-5">
    <div class="container-fluid">
        <div class="row align-items-center">
            <div class="col-lg-8">
                <div class="d-flex align-items-center mb-3">
                    <div class="widget-icon bg-white bg-opacity-15 me-4">
                        <i class="fas fa-chart-line text-white"></i>
                    </div>
                    <div>
                        <h1 class="display-5 fw-bold mb-0">Dashboard Executivo</h1>
                        <p class="fs-5 mb-0 opacity-90">Sistema BC - Inteligência Financeira</p>
                    </div>
                </div>
                <div class="row mt-4">
                    <div class="col-auto">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-calendar-check me-2 opacity-75"></i>
                            <span class="opacity-90">{{ now()->format('l, d \d\e F \d\e Y') }}</span>
                        </div>
                    </div>
                    <div class="col-auto">
                        <div class="d-flex align-items-center">
                            <i class="fas fa-clock me-2 opacity-75"></i>
                            <span class="opacity-90">Atualizado às {{ now()->format('H:i') }}</span>
                        </div>
                    </div>
                    <div class="col-auto">
                        <span class="performance-indicator">
                            <i class="fas fa-check-circle me-1"></i>Sistema Online
                        </span>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 text-end">
                <div class="d-flex flex-wrap gap-3 justify-content-end">
                    <button class="action-button" onclick="refreshDashboard()">
                        <i class="fas fa-sync-alt me-2"></i>Atualizar Dados
                    </button>
                    <div class="dropdown">
                        <button class="action-button dropdown-toggle" data-bs-toggle="dropdown">
                            <i class="fas fa-download me-2"></i>Relatórios
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="#" onclick="exportDashboard('pdf')">
                                <i class="fas fa-file-pdf me-2 text-danger"></i>Relatório Executivo PDF
                            </a></li>
                            <li><a class="dropdown-item" href="#" onclick="exportDashboard('excel')">
                                <i class="fas fa-file-excel me-2 text-success"></i>Dados em Excel
                            </a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="{{ route('reports.financial-management') }}">
                                <i class="fas fa-chart-bar me-2 text-primary"></i>Relatório Completo
                            </a></li>
                        </ul>
                    </div>
                    <button class="action-button" data-bs-toggle="modal" data-bs-target="#quickActionsModal">
                        <i class="fas fa-plus me-2"></i>Nova Operação
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('content')
<div class="dashboard-container">
    <div class="container-fluid">
        <!-- Métricas Executivas -->
        <div class="row mb-5">
            <div class="col-xl-3 col-lg-6 mb-4">
                <div class="executive-card h-100">
                    <div class="card-body p-4">
                        <div class="row align-items-center">
                            <div class="col-8">
                                <h6 class="text-muted fw-semibold mb-2">CONTAS BANCÁRIAS</h6>
                                <div class="metric-display">{{ $stats['active_accounts'] ?? 0 }}</div>
                                <div class="performance-indicator mt-2">
                                    <i class="fas fa-check-circle me-1"></i>{{ $stats['active_accounts'] ?? 0 }}/{{ $stats['total_accounts'] ?? 0 }} Ativas
                                </div>
                            </div>
                            <div class="col-4 text-end">
                                <div class="widget-icon" style="background: var(--primary-gradient);">
                                    <i class="fas fa-university text-white"></i>
                                </div>
                            </div>
                        </div>
                        <div class="progress mt-3" style="height: 6px; border-radius: 10px;">
                            <div class="progress-bar" style="background: var(--primary-gradient); width: 100%; border-radius: 10px;"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-lg-6 mb-4">
                <div class="executive-card h-100">
                    <div class="card-body p-4">
                        <div class="row align-items-center">
                            <div class="col-8">
                                <h6 class="text-muted fw-semibold mb-2">SALDO TOTAL</h6>
                                <div class="metric-display text-success">{{ number_format($stats['total_balance'] ?? 0, 0, ',', '.') }}</div>
                                <div class="performance-indicator mt-2" style="background: var(--success-gradient);">
                                    <i class="fas fa-trending-up me-1"></i>Patrimônio
                                </div>
                            </div>
                            <div class="col-4 text-end">
                                <div class="widget-icon" style="background: var(--success-gradient);">
                                    <i class="fas fa-wallet text-white"></i>
                                </div>
                            </div>
                        </div>
                        <div class="progress mt-3" style="height: 6px; border-radius: 10px;">
                            <div class="progress-bar" style="background: var(--success-gradient); width: 90%; border-radius: 10px;"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-lg-6 mb-4">
                <div class="executive-card h-100">
                    <div class="card-body p-4">
                        <div class="row align-items-center">
                            <div class="col-8">
                                <h6 class="text-muted fw-semibold mb-2">TRANSAÇÕES</h6>
                                <div class="metric-display text-info">{{ $stats['total_transactions'] ?? 0 }}</div>
                                <div class="performance-indicator mt-2" style="background: var(--info-gradient);">
                                    <i class="fas fa-clock me-1"></i>{{ $stats['pending_transactions'] ?? 0 }} Pendentes
                                </div>
                            </div>
                            <div class="col-4 text-end">
                                <div class="widget-icon" style="background: var(--info-gradient);">
                                    <i class="fas fa-exchange-alt text-white"></i>
                                </div>
                            </div>
                        </div>
                        <div class="progress mt-3" style="height: 6px; border-radius: 10px;">
                            <div class="progress-bar" style="background: var(--info-gradient); width: 75%; border-radius: 10px;"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-lg-6 mb-4">
                <div class="executive-card h-100">
                    <div class="card-body p-4">
                        <div class="row align-items-center">
                            <div class="col-8">
                                <h6 class="text-muted fw-semibold mb-2">CONCILIAÇÕES</h6>
                                <div class="metric-display text-warning">{{ $stats['month_reconciliations'] ?? 0 }}</div>
                                <div class="performance-indicator mt-2" style="background: var(--warning-gradient);">
                                    <i class="fas fa-balance-scale me-1"></i>Este Mês
                                </div>
                            </div>
                            <div class="col-4 text-end">
                                <div class="widget-icon" style="background: var(--warning-gradient);">
                                    <i class="fas fa-check-double text-white"></i>
                                </div>
                            </div>
                        </div>
                        <div class="progress mt-3" style="height: 6px; border-radius: 10px;">
                            <div class="progress-bar" style="background: var(--warning-gradient); width: 85%; border-radius: 10px;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Análises e Gráficos -->
        <div class="row mb-5">
            <div class="col-lg-8">
                <div class="chart-professional">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <div>
                            <h4 class="fw-bold mb-1">
                                <i class="fas fa-chart-area text-primary me-2"></i>
                                Performance Financeira
                            </h4>
                            <p class="text-muted mb-0">Análise de tendências e movimentação</p>
                        </div>
                        <div class="btn-group">
                            <button class="btn btn-outline-primary active" onclick="changeChartPeriod('7')">7 dias</button>
                            <button class="btn btn-outline-primary" onclick="changeChartPeriod('30')">30 dias</button>
                            <button class="btn btn-outline-primary" onclick="changeChartPeriod('90')">90 dias</button>
                        </div>
                    </div>
                    <canvas id="financialChart" width="400" height="300"></canvas>
                </div>
            </div>
            
            <div class="col-lg-4">
                <div class="chart-professional">
                    <div class="mb-4">
                        <h5 class="fw-bold mb-1">
                            <i class="fas fa-chart-pie text-secondary me-2"></i>
                            Distribuição de Categorias
                        </h5>
                        <p class="text-muted mb-0">Análise por tipo de transação</p>
                    </div>
                    <canvas id="categoryChart" width="300" height="250"></canvas>
                </div>
            </div>
        </div>

        <!-- Ações Rápidas -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="financial-widget">
                    <div class="d-flex align-items-center justify-content-between mb-4">
                        <div>
                            <h4 class="fw-bold mb-1">
                                <i class="fas fa-bolt text-warning me-2"></i>
                                Ações Rápidas
                            </h4>
                            <p class="text-muted mb-0">Acesso direto às funcionalidades principais</p>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-lg-2 col-md-4 col-6 mb-3">
                            <a href="{{ route('clients.create') }}" class="btn btn-light btn-lg w-100 h-100 d-flex flex-column align-items-center justify-content-center p-4 text-decoration-none">
                                <div class="widget-icon mb-2" style="background: var(--success-gradient); width: 60px; height: 60px;">
                                    <i class="fas fa-user-plus text-white"></i>
                                </div>
                                <span class="fw-semibold text-dark">Novo Cliente</span>
                            </a>
                        </div>
                        <div class="col-lg-2 col-md-4 col-6 mb-3">
                            <a href="{{ route('suppliers.create') }}" class="btn btn-light btn-lg w-100 h-100 d-flex flex-column align-items-center justify-content-center p-4 text-decoration-none">
                                <div class="widget-icon mb-2" style="background: var(--info-gradient); width: 60px; height: 60px;">
                                    <i class="fas fa-building text-white"></i>
                                </div>
                                <span class="fw-semibold text-dark">Novo Fornecedor</span>
                            </a>
                        </div>
                        <div class="col-lg-2 col-md-4 col-6 mb-3">
                            <a href="{{ route('account-payables.create') }}" class="btn btn-light btn-lg w-100 h-100 d-flex flex-column align-items-center justify-content-center p-4 text-decoration-none">
                                <div class="widget-icon mb-2" style="background: var(--danger-gradient); width: 60px; height: 60px;">
                                    <i class="fas fa-file-invoice-dollar text-white"></i>
                                </div>
                                <span class="fw-semibold text-dark">Conta a Pagar</span>
                            </a>
                        </div>
                        <div class="col-lg-2 col-md-4 col-6 mb-3">
                            <a href="{{ route('account-receivables.create') }}" class="btn btn-light btn-lg w-100 h-100 d-flex flex-column align-items-center justify-content-center p-4 text-decoration-none">
                                <div class="widget-icon mb-2" style="background: var(--warning-gradient); width: 60px; height: 60px;">
                                    <i class="fas fa-file-invoice text-white"></i>
                                </div>
                                <span class="fw-semibold text-dark">Conta a Receber</span>
                            </a>
                        </div>
                        <div class="col-lg-2 col-md-4 col-6 mb-3">
                            <a href="{{ route('transactions.create') }}" class="btn btn-light btn-lg w-100 h-100 d-flex flex-column align-items-center justify-content-center p-4 text-decoration-none">
                                <div class="widget-icon mb-2" style="background: var(--primary-gradient); width: 60px; height: 60px;">
                                    <i class="fas fa-exchange-alt text-white"></i>
                                </div>
                                <span class="fw-semibold text-dark">Nova Transação</span>
                            </a>
                        </div>
                        <div class="col-lg-2 col-md-4 col-6 mb-3">
                            <a href="{{ route('reconciliations.create') }}" class="btn btn-light btn-lg w-100 h-100 d-flex flex-column align-items-center justify-content-center p-4 text-decoration-none">
                                <div class="widget-icon mb-2" style="background: var(--info-gradient); width: 60px; height: 60px;">
                                    <i class="fas fa-balance-scale text-white"></i>
                                </div>
                                <span class="fw-semibold text-dark">Conciliação</span>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-bs-toggle="tab" href="#reconciliations-tab">
                    <i class="fas fa-balance-scale me-2"></i>Conciliações Recentes
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-bs-toggle="tab" href="#alerts-tab">
                    <i class="fas fa-exclamation-triangle me-2"></i>Alertas
                    @if(isset($alerts) && count($alerts) > 0)
                        <span class="badge bg-danger ms-1">{{ count($alerts) }}</span>
                    @endif
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-bs-toggle="tab" href="#summary-tab">
                    <i class="fas fa-chart-bar me-2"></i>Resumo Mensal
                </a>
            </li>
        </ul>
    </div>
    
    <div class="card-body">
        <div class="tab-content">
            <!-- Tab de Transações -->
            <div class="tab-pane fade show active" id="transactions-tab">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-0">Últimas 10 Transações</h6>
                    <a href="{{ route('transactions.index') }}" class="btn btn-sm btn-outline-primary">
                        <i class="fas fa-list me-2"></i>Ver Todas
                    </a>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th class="border-0">
                                    <i class="fas fa-calendar me-2 text-muted"></i>Data
                                </th>
                                <th class="border-0">
                                    <i class="fas fa-university me-2 text-muted"></i>Conta
                                </th>
                                <th class="border-0">
                                    <i class="fas fa-file-text me-2 text-muted"></i>Descrição
                                </th>
                                <th class="border-0 text-end">
                                    <i class="fas fa-dollar-sign me-2 text-muted"></i>Valor
                                </th>
                                <th class="border-0 text-center">
                                    <i class="fas fa-info-circle me-2 text-muted"></i>Status
                                </th>
                                <th class="border-0 text-center">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($recentTransactions ?? [] as $transaction)
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="bg-light rounded p-2 me-2">
                                            <i class="fas fa-calendar-day text-primary small"></i>
                                        </div>
                                        <div class="small">
                                            <strong>{{ $transaction->transaction_date ? $transaction->transaction_date->format('d/m/Y') : 'N/A' }}</strong>
                                            <br>
                                            <span class="text-muted">{{ $transaction->transaction_date ? $transaction->transaction_date->format('H:i') : '00:00' }}</span>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <div class="small">
                                        <strong>{{ $transaction->bankAccount->name ?? 'Conta não informada' }}</strong>
                                        <br>
                                        <span class="text-muted">{{ $transaction->bankAccount->bank_name ?? 'Banco não informado' }}</span>
                                    </div>
                                </td>
                                <td>
                                    <div class="small">
                                        <strong>{{ Str::limit($transaction->description ?? 'Sem descrição', 40) }}</strong>
                                        @if($transaction->category)
                                            <br>
                                            <span class="badge bg-secondary">{{ $transaction->category }}</span>
                                        @endif
                                    </div>
                                </td>
                                <td class="text-end">
                                    <span class="fw-bold {{ ($transaction->type ?? 'debit') == 'credit' ? 'text-success' : 'text-danger' }}">
                                        <i class="fas fa-{{ ($transaction->type ?? 'debit') == 'credit' ? 'plus' : 'minus' }}-circle me-1"></i>
                                        {{ $transaction->formatted_amount ?? 'R$ 0,00' }}
                                    </span>
                                </td>
                                <td class="text-center">
                                    <span class="badge bg-{{ ($transaction->status ?? 'pending') == 'reconciled' ? 'success' : (($transaction->status ?? 'pending') == 'pending' ? 'warning' : 'secondary') }} fs-6">
                                        <i class="fas fa-{{ ($transaction->status ?? 'pending') == 'reconciled' ? 'check' : 'clock' }} me-1"></i>
                                        {{ ($transaction->status ?? 'pending') == 'reconciled' ? 'Conciliado' : 'Pendente' }}
                                    </span>
                                </td>
                                <td class="text-center">
                                    <div class="btn-group btn-group-sm">
                                        <a href="{{ route('transactions.show', $transaction) }}" 
                                           class="btn btn-outline-primary" title="Ver Detalhes">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        @if(($transaction->status ?? 'pending') != 'reconciled')
                                            <a href="{{ route('transactions.edit', $transaction) }}" 
                                               class="btn btn-outline-secondary" title="Editar">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                        @endif
                                    </div>
                                </td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="6" class="text-center py-4">
                                    <div class="py-3">
                                        <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                                        <h6 class="text-muted">Nenhuma transação encontrada</h6>
                                        <p class="text-muted mb-0">Não há transações recentes para exibir.</p>
                                    </div>
                                </td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Tab de Conciliações -->
            <div class="tab-pane fade" id="reconciliations-tab">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-0">Conciliações Recentes</h6>
                    <a href="{{ route('reconciliations.index') }}" class="btn btn-sm btn-outline-primary">
                        <i class="fas fa-balance-scale me-2"></i>Ver Todas
                    </a>
                </div>
                
                @if(isset($recentReconciliations) && $recentReconciliations->count() > 0)
                <div class="row">
                    @foreach($recentReconciliations as $reconciliation)
                    <div class="col-md-6 mb-3">
                        <div class="card border-0 shadow-sm">
                            <div class="card-body">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <h6 class="mb-0">{{ $reconciliation->bankAccount->name }}</h6>
                                    @php
                                        $statusConfig = [
                                            'approved' => ['class' => 'success', 'icon' => 'check-circle', 'text' => 'Aprovada'],
                                            'completed' => ['class' => 'info', 'icon' => 'clock', 'text' => 'Completa'],
                                            'draft' => ['class' => 'warning', 'icon' => 'edit', 'text' => 'Rascunho']
                                        ];
                                        $config = $statusConfig[$reconciliation->status] ?? $statusConfig['draft'];
                                    @endphp
                                    <span class="badge bg-{{ $config['class'] }}">
                                        <i class="fas fa-{{ $config['icon'] }} me-1"></i>
                                        {{ $config['text'] }}
                                    </span>
                                </div>
                                <small class="text-muted">
                                    {{ $reconciliation->start_date->format('d/m/Y') }} - {{ $reconciliation->end_date->format('d/m/Y') }}
                                </small>
                                <div class="row mt-2">
                                    <div class="col-6">
                                        <small class="text-muted">Saldo Final</small>
                                        <div class="fw-bold text-primary">
                                            R$ {{ number_format($reconciliation->ending_balance, 2, ',', '.') }}
                                        </div>
                                    </div>
                                    <div class="col-6">
                                        <small class="text-muted">Diferença</small>
                                        <div class="fw-bold {{ $reconciliation->isBalanced() ? 'text-success' : 'text-danger' }}">
                                            R$ {{ number_format(abs($reconciliation->difference ?? 0), 2, ',', '.') }}
                                        </div>
                                    </div>
                                </div>
                                <div class="text-end mt-2">
                                    <a href="{{ route('reconciliations.show', $reconciliation) }}" class="btn btn-sm btn-outline-primary">
                                        Ver Detalhes
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    @endforeach
                </div>
                @else
                <div class="text-center py-4">
                    <i class="fas fa-balance-scale fa-3x text-muted mb-3"></i>
                    <h6 class="text-muted">Nenhuma conciliação recente</h6>
                    <p class="text-muted mb-3">Não há conciliações recentes para exibir.</p>
                    <a href="{{ route('reconciliations.create') }}" class="btn btn-primary">
                        <i class="fas fa-plus me-2"></i>Nova Conciliação
                    </a>
                </div>
                @endif
            </div>
            
            <!-- Tab de Alertas -->
            <div class="tab-pane fade" id="alerts-tab">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-0">Alertas e Notificações</h6>
                    <button class="btn btn-sm btn-outline-secondary" onclick="markAllAsRead()">
                        <i class="fas fa-check-double me-2"></i>Marcar como Lidas
                    </button>
                </div>
                
                @if(isset($alerts) && count($alerts) > 0)
                <div class="list-group list-group-flush">
                    @foreach($alerts as $alert)
                    <div class="list-group-item border-0 px-0">
                        <div class="d-flex align-items-start">
                            <div class="bg-{{ $alert['type'] == 'warning' ? 'warning' : ($alert['type'] == 'error' ? 'danger' : 'info') }} bg-opacity-25 rounded p-2 me-3">
                                <i class="fas fa-{{ $alert['type'] == 'warning' ? 'exclamation-triangle' : ($alert['type'] == 'error' ? 'times-circle' : 'info-circle') }} text-{{ $alert['type'] == 'warning' ? 'warning' : ($alert['type'] == 'error' ? 'danger' : 'info') }}"></i>
                            </div>
                            <div class="flex-grow-1">
                                <h6 class="mb-1">{{ $alert['title'] }}</h6>
                                <p class="text-muted mb-1">{{ $alert['message'] }}</p>
                                <small class="text-muted">Agora mesmo</small>
                            </div>
                            <button class="btn btn-sm btn-outline-secondary" onclick="window.location.href='{{ $alert->action ?? '#' }}'">
                                <i class="fas fa-arrow-right"></i>
                            </button>
                        </div>
                    </div>
                    @endforeach
                </div>
                @else
                <div class="text-center py-4">
                    <i class="fas fa-check-circle fa-3x text-success mb-3"></i>
                    <h6 class="text-muted">Tudo em ordem!</h6>
                    <p class="text-muted mb-0">Não há alertas pendentes no momento.</p>
                </div>
                @endif
            </div>
            
            <!-- Tab de Resumo Mensal -->
            <div class="tab-pane fade" id="summary-tab">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="mb-0">Resumo Mensal - {{ now()->format('F Y') }}</h6>
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-secondary" onclick="changeSummaryMonth(-1)">
                            <i class="fas fa-chevron-left"></i>
                        </button>
                        <button class="btn btn-outline-secondary" onclick="changeSummaryMonth(1)">
                            <i class="fas fa-chevron-right"></i>
                        </button>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <div class="card border-0 bg-success bg-opacity-10">
                            <div class="card-body text-center">
                                <i class="fas fa-arrow-up fa-2x text-success mb-2"></i>
                                <h6 class="text-muted">Total de Entradas</h6>
                                <h4 class="text-success">R$ {{ number_format($monthlySummary['credits'] ?? 0, 2, ',', '.') }}</h4>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="card border-0 bg-danger bg-opacity-10">
                            <div class="card-body text-center">
                                <i class="fas fa-arrow-down fa-2x text-danger mb-2"></i>
                                <h6 class="text-muted">Total de Saídas</h6>
                                <h4 class="text-danger">R$ {{ number_format($monthlySummary['debits'] ?? 0, 2, ',', '.') }}</h4>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <div class="card border-0 bg-primary bg-opacity-10">
                            <div class="card-body text-center">
                                <i class="fas fa-balance-scale fa-2x text-primary mb-2"></i>
                                <h6 class="text-muted">Saldo Líquido</h6>
                                @php $netBalance = ($monthlySummary['credits'] ?? 0) - ($monthlySummary['debits'] ?? 0); @endphp
                                <h4 class="{{ $netBalance >= 0 ? 'text-success' : 'text-danger' }}">
                                    R$ {{ number_format($netBalance, 2, ',', '.') }}
                                </h4>
                            </div>
                        </div>
                    </div>
                </div>
                
                @if(isset($monthlyStats))
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="mb-3">Principais Categorias (Saídas)</h6>
                        @foreach($monthlyStats['top_categories'] ?? [] as $category)
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="text-muted">{{ $category['name'] }}</span>
                            <span class="fw-bold text-danger">R$ {{ number_format($category['total'], 2, ',', '.') }}</span>
                        </div>
                        @endforeach
                    </div>
                    <div class="col-md-6">
                        <h6 class="mb-3">Estatísticas do Período</h6>
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="text-muted">Total de Transações</span>
                            <span class="fw-bold">{{ $monthlyStats['total_transactions'] ?? 0 }}</span>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="text-muted">Média por Dia</span>
                            <span class="fw-bold">{{ number_format(($monthlyStats['daily_average'] ?? 0), 2, ',', '.') }}</span>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span class="text-muted">Conciliações Realizadas</span>
                            <span class="fw-bold">{{ $monthlyStats['reconciliations_count'] ?? 0 }}</span>
                        </div>
                    </div>
                </div>
                @endif
            </div>
        </div>
    </div>
</div>

        <!-- Gestão Financeira Executiva -->
        @if(isset($financialManagement))
        <div class="row mb-5">
            <div class="col-12">
                <div class="financial-widget">
                    <div class="d-flex align-items-center justify-content-between mb-4">
                        <div class="d-flex align-items-center">
                            <div class="widget-icon me-3" style="background: var(--primary-gradient);">
                                <i class="fas fa-chart-pie text-white"></i>
                            </div>
                            <div>
                                <h3 class="fw-bold mb-1">Inteligência Financeira</h3>
                                <p class="text-muted mb-0">Análise completa do fluxo de caixa e contas</p>
                            </div>
                        </div>
                        <a href="{{ route('reports.financial-management') }}" class="btn btn-outline-primary btn-lg">
                            <i class="fas fa-external-link-alt me-2"></i>Ver Relatório Completo
                        </a>
                    </div>

                    <!-- KPIs Financeiros -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-lg-6 mb-3">
                            <div class="executive-card" style="background: var(--success-gradient); color: white;">
                                <div class="card-body p-4 text-center">
                                    <div class="widget-icon mx-auto mb-3" style="background: rgba(255,255,255,0.2);">
                                        <i class="fas fa-arrow-circle-down text-white"></i>
                                    </div>
                                    <h6 class="fw-semibold opacity-90">VALORES A RECEBER</h6>
                                    <div class="display-6 fw-bold">R$ {{ number_format($financialManagement['cashFlow']['to_receive'], 0, ',', '.') }}</div>
                                    <div class="mt-2 opacity-90">
                                        <i class="fas fa-file-invoice me-1"></i>
                                        {{ $financialManagement['accountsReceivable']['pending'] + $financialManagement['accountsReceivable']['overdue'] }} contas em aberto
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-lg-6 mb-3">
                            <div class="executive-card" style="background: var(--danger-gradient); color: white;">
                                <div class="card-body p-4 text-center">
                                    <div class="widget-icon mx-auto mb-3" style="background: rgba(255,255,255,0.2);">
                                        <i class="fas fa-arrow-circle-up text-white"></i>
                                    </div>
                                    <h6 class="fw-semibold opacity-90">VALORES A PAGAR</h6>
                                    <div class="display-6 fw-bold">R$ {{ number_format($financialManagement['cashFlow']['to_pay'], 0, ',', '.') }}</div>
                                    <div class="mt-2 opacity-90">
                                        <i class="fas fa-file-invoice-dollar me-1"></i>
                                        {{ $financialManagement['accountsPayable']['pending'] + $financialManagement['accountsPayable']['overdue'] }} contas pendentes
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-lg-6 mb-3">
                            <div class="executive-card" style="background: {{ $financialManagement['cashFlow']['balance'] >= 0 ? 'var(--primary-gradient)' : 'var(--warning-gradient)' }}; color: white;">
                                <div class="card-body p-4 text-center">
                                    <div class="widget-icon mx-auto mb-3" style="background: rgba(255,255,255,0.2);">
                                        <i class="fas fa-balance-scale-right text-white"></i>
                                    </div>
                                    <h6 class="fw-semibold opacity-90">SALDO PROJETADO</h6>
                                    <div class="display-6 fw-bold">R$ {{ number_format($financialManagement['cashFlow']['balance'], 0, ',', '.') }}</div>
                                    <div class="mt-2 opacity-90">
                                        <i class="fas fa-{{ $financialManagement['cashFlow']['balance'] >= 0 ? 'trending-up' : 'trending-down' }} me-1"></i>
                                        {{ $financialManagement['cashFlow']['balance'] >= 0 ? 'Positivo' : 'Atenção Necessária' }}
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-lg-6 mb-3">
                            <div class="executive-card" style="background: var(--info-gradient); color: white;">
                                <div class="card-body p-4 text-center">
                                    <div class="widget-icon mx-auto mb-3" style="background: rgba(255,255,255,0.2);">
                                        <i class="fas fa-users-cog text-white"></i>
                                    </div>
                                    <h6 class="fw-semibold opacity-90">CLIENTES & FORNECEDORES</h6>
                                    <div class="display-6 fw-bold">{{ $stats['total_clients'] + $stats['total_suppliers'] }}</div>
                                    <div class="mt-2 opacity-90">
                                        <i class="fas fa-user-friends me-1"></i>
                                        {{ $stats['total_clients'] }} clientes · {{ $stats['total_suppliers'] }} fornecedores
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Alertas Inteligentes -->
                    <div class="row">
                        <div class="col-lg-6 mb-4">
                            <div class="executive-card h-100">
                                <div class="card-header bg-warning text-dark p-4">
                                    <h5 class="mb-0 fw-bold">
                                        <i class="fas fa-exclamation-triangle me-2"></i>
                                        Contas a Pagar - Vencimentos Próximos
                                    </h5>
                                </div>
                                <div class="card-body p-4">
                                    @if($financialManagement['upcomingPayables']->count() > 0)
                                        <div class="list-group list-group-flush">
                                            @foreach($financialManagement['upcomingPayables'] as $payable)
                                            <div class="list-group-item border-0 px-0 py-3">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <div class="d-flex align-items-center">
                                                        <div class="widget-icon me-3" style="width: 50px; height: 50px; background: var(--warning-gradient);">
                                                            <i class="fas fa-building text-white"></i>
                                                        </div>
                                                        <div>
                                                            <h6 class="fw-bold mb-0">{{ $payable->supplier->name }}</h6>
                                                            <p class="text-muted mb-0">{{ $payable->description }}</p>
                                                        </div>
                                                    </div>
                                                    <div class="text-end">
                                                        <div class="status-badge bg-warning text-dark">{{ $payable->formatted_amount }}</div>
                                                        <small class="text-muted d-block mt-1">{{ $payable->due_date->format('d/m/Y') }}</small>
                                                    </div>
                                                </div>
                                            </div>
                                            @endforeach
                                        </div>
                                        <div class="text-center mt-4">
                                            <a href="{{ route('account-payables.index') }}" class="btn btn-warning btn-lg fw-semibold">
                                                <i class="fas fa-list me-2"></i>Gerenciar Todas as Contas a Pagar
                                            </a>
                                        </div>
                                    @else
                                        <div class="text-center py-5">
                                            <i class="fas fa-check-circle fa-3x text-success mb-3"></i>
                                            <h5 class="text-success">Excelente!</h5>
                                            <p class="text-muted">Nenhuma conta a pagar vencendo nos próximos 7 dias.</p>
                                        </div>
                                    @endif
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-lg-6 mb-4">
                            <div class="executive-card h-100">
                                <div class="card-header bg-success text-white p-4">
                                    <h5 class="mb-0 fw-bold">
                                        <i class="fas fa-check-circle me-2"></i>
                                        Contas a Receber - Vencimentos Próximos
                                    </h5>
                                </div>
                                <div class="card-body p-4">
                                    @if($financialManagement['upcomingReceivables']->count() > 0)
                                        <div class="list-group list-group-flush">
                                            @foreach($financialManagement['upcomingReceivables'] as $receivable)
                                            <div class="list-group-item border-0 px-0 py-3">
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <div class="d-flex align-items-center">
                                                        <div class="widget-icon me-3" style="width: 50px; height: 50px; background: var(--success-gradient);">
                                                            <i class="fas fa-user-tie text-white"></i>
                                                        </div>
                                                        <div>
                                                            <h6 class="fw-bold mb-0">{{ $receivable->client->name }}</h6>
                                                            <p class="text-muted mb-0">{{ $receivable->description }}</p>
                                                        </div>
                                                    </div>
                                                    <div class="text-end">
                                                        <div class="status-badge bg-success text-white">{{ $receivable->formatted_amount }}</div>
                                                        <small class="text-muted d-block mt-1">{{ $receivable->due_date->format('d/m/Y') }}</small>
                                                    </div>
                                                </div>
                                            </div>
                                            @endforeach
                                        </div>
                                        <div class="text-center mt-4">
                                            <a href="{{ route('account-receivables.index') }}" class="btn btn-success btn-lg fw-semibold">
                                                <i class="fas fa-list me-2"></i>Gerenciar Todas as Contas a Receber
                                            </a>
                                        </div>
                                    @else
                                        <div class="text-center py-5">
                                            <i class="fas fa-info-circle fa-3x text-info mb-3"></i>
                                            <h5 class="text-info">Nenhum vencimento próximo</h5>
                                            <p class="text-muted">Sem contas a receber vencendo nos próximos 7 dias.</p>
                                        </div>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Alertas Críticos -->
                    @if($financialManagement['overduePayables']->count() > 0 || $financialManagement['overdueReceivables']->count() > 0)
                    <div class="row mt-4">
                        <div class="col-12">
                            <div class="alert-professional border-danger p-4">
                                <div class="d-flex align-items-center mb-3">
                                    <div class="widget-icon me-3" style="background: var(--danger-gradient);">
                                        <i class="fas fa-exclamation-triangle text-white"></i>
                                    </div>
                                    <div>
                                        <h4 class="fw-bold text-danger mb-0">Atenção: Contas Vencidas Detectadas</h4>
                                        <p class="text-muted mb-0">Requer ação imediata para regularização</p>
                                    </div>
                                </div>
                                <div class="row">
                                    @if($financialManagement['overduePayables']->count() > 0)
                                    <div class="col-md-6">
                                        <div class="bg-danger bg-opacity-10 p-3 rounded">
                                            <h6 class="text-danger fw-bold">
                                                <i class="fas fa-arrow-up me-1"></i>
                                                Contas a Pagar Vencidas ({{ $financialManagement['overduePayables']->count() }})
                                            </h6>
                                            <ul class="list-unstyled mt-2 mb-0">
                                                @foreach($financialManagement['overduePayables'] as $overdue)
                                                <li class="mb-1">
                                                    <strong>{{ $overdue->supplier->name }}</strong> - {{ $overdue->formatted_amount }} 
                                                    <small class="text-muted">({{ $overdue->due_date->format('d/m/Y') }})</small>
                                                </li>
                                                @endforeach
                                            </ul>
                                        </div>
                                    </div>
                                    @endif
                                    @if($financialManagement['overdueReceivables']->count() > 0)
                                    <div class="col-md-6">
                                        <div class="bg-warning bg-opacity-10 p-3 rounded">
                                            <h6 class="text-warning fw-bold">
                                                <i class="fas fa-arrow-down me-1"></i>
                                                Contas a Receber Vencidas ({{ $financialManagement['overdueReceivables']->count() }})
                                            </h6>
                                            <ul class="list-unstyled mt-2 mb-0">
                                                @foreach($financialManagement['overdueReceivables'] as $overdue)
                                                <li class="mb-1">
                                                    <strong>{{ $overdue->client->name }}</strong> - {{ $overdue->formatted_amount }} 
                                                    <small class="text-muted">({{ $overdue->due_date->format('d/m/Y') }})</small>
                                                </li>
                                                @endforeach
                                            </ul>
                                        </div>
                                    </div>
                                    @endif
                                </div>
                            </div>
                        </div>
                    </div>
                    @endif
                </div>
            </div>
        </div>
        @endif

<!-- Modal de Ações Rápidas -->
<div class="modal fade" id="quickActionsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-bolt me-2"></i>Ações Rápidas
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-6 mb-3">
                        <a href="{{ route('transactions.create') }}" class="btn btn-outline-primary w-100">
                            <i class="fas fa-plus mb-2 d-block"></i>
                            Nova Transação
                        </a>
                    </div>
                    <div class="col-6 mb-3">
                        <a href="{{ route('reconciliations.create') }}" class="btn btn-outline-success w-100">
                            <i class="fas fa-balance-scale mb-2 d-block"></i>
                            Nova Conciliação
                        </a>
                    </div>
                    <div class="col-6 mb-3">
                        <a href="{{ route('imports.create') }}" class="btn btn-outline-info w-100">
                            <i class="fas fa-upload mb-2 d-block"></i>
                            Importar Extrato
                        </a>
                    </div>
                    <div class="col-6 mb-3">
                        <a href="{{ route('reports.index') }}" class="btn btn-outline-warning w-100">
                            <i class="fas fa-chart-bar mb-2 d-block"></i>
                            Gerar Relatório
                        </a>
                    </div>
                    <div class="col-6">
                        <a href="{{ route('categories.create') }}" class="btn btn-outline-secondary w-100">
                            <i class="fas fa-tag mb-2 d-block"></i>
                            Nova Categoria
                        </a>
                    </div>
                    <div class="col-6">
                        <a href="{{ route('bank-accounts.create') }}" class="btn btn-outline-dark w-100">
                            <i class="fas fa-university mb-2 d-block"></i>
                            Nova Conta
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Toast para loading -->
<div class="toast-container position-fixed bottom-0 end-0 p-3">
    <div id="loadingToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="toast-header">
            <i class="fas fa-spinner fa-spin me-2"></i>
            <strong class="me-auto">Atualizando</strong>
        </div>
        <div class="toast-body">
            Carregando dados do dashboard...
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
.hover-lift {
    transition: all 0.3s ease;
}

.hover-lift:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.15) !important;
}

.nav-tabs .nav-link {
    border: none;
    color: #6c757d;
    font-weight: 500;
}

.nav-tabs .nav-link.active {
    color: #0d6efd;
    border-bottom: 2px solid #0d6efd;
}

.nav-tabs .nav-link:hover {
    color: #0d6efd;
    border-color: transparent;
}

.list-group-item {
    transition: all 0.2s ease;
}

.list-group-item:hover {
    background-color: #f8f9fa;
}

@media (max-width: 768px) {
    .card-body {
        padding: 1rem;
    }
    
    .btn-group-sm .btn {
        padding: 0.25rem 0.5rem;
        font-size: 0.75rem;
    }
}

#financialChart, #categoryChart {
    max-height: 300px;
}
</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
$(document).ready(function() {
    // Inicializar gráficos
    initializeFinancialChart();
    initializeCategoryChart();
    
    // Auto-refresh a cada 5 minutos
    setInterval(function() {
        refreshDashboard();
    }, 5 * 60 * 1000);
});

function initializeFinancialChart() {
    const ctx = document.getElementById('financialChart').getContext('2d');
    
    // Dados reais do backend
    const chartData = @json($chartData['monthly'] ?? ['labels' => [], 'datasets' => []]);
    
    new Chart(ctx, {
        type: 'line',
        data: chartData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        padding: 20
                    }
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    callbacks: {
                        label: function(context) {
                            return context.dataset.label + ': ' + formatCurrency(context.parsed.y);
                        }
                    }
                }
            },
            scales: {
                x: {
                    display: true,
                    title: {
                        display: true,
                        text: 'Período'
                    }
                },
                y: {
                    display: true,
                    title: {
                        display: true,
                        text: 'Valor (R$)'
                    },
                    ticks: {
                        callback: function(value) {
                            return formatCurrency(value);
                        }
                    }
                }
            },
            interaction: {
                mode: 'nearest',
                axis: 'x',
                intersect: false
            }
        }
    });
}

function initializeCategoryChart() {
    const ctx = document.getElementById('categoryChart').getContext('2d');
    
    // Dados reais do backend
    const chartData = @json($chartData['categories'] ?? ['labels' => [], 'datasets' => []]);
    
    if (chartData.labels.length === 0) {
        ctx.font = '16px Arial';
        ctx.fillStyle = '#666';
        ctx.textAlign = 'center';
        ctx.fillText('Nenhum dado disponível', 150, 150);
        return;
    }
    
    new Chart(ctx, {
        type: 'doughnut',
        data: chartData,
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        usePointStyle: true,
                        padding: 15,
                        generateLabels: function(chart) {
                            const data = chart.data;
                            if (data.labels.length && data.datasets.length) {
                                return data.labels.map((label, i) => {
                                    const dataset = data.datasets[0];
                                    const value = dataset.data[i];
                                    const total = dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((value / total) * 100).toFixed(1);
                                    
                                    return {
                                        text: `${label} (${percentage}%)`,
                                        fillStyle: dataset.backgroundColor[i],
                                        strokeStyle: dataset.borderColor || '#fff',
                                        lineWidth: 2,
                                        hidden: false,
                                        index: i
                                    };
                                });
                            }
                            return [];
                        }
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const percentage = ((context.parsed / total) * 100).toFixed(1);
                            return context.label + ': ' + context.parsed + ' (' + percentage + '%)';
                        }
                    }
                }
            }
        });
}

function refreshDashboard() {
    // Mostrar loading
    const loadingToast = new bootstrap.Toast(document.getElementById('loadingToast'));
    if (loadingToast) {
        loadingToast.show();
    }
    
    $.ajax({
        url: window.location.href,
        type: 'GET',
        data: { ajax: 1 },
        success: function(response) {
            // Atualizar estatísticas
            if (response.stats) {
                updateStats(response.stats);
            }
            
            // Recarregar gráficos
            location.reload();
        },
        error: function(xhr, status, error) {
            console.error('Erro ao atualizar dashboard:', error);
            
            // Mostrar erro
            const errorAlert = `
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    Erro ao atualizar dashboard. Tente novamente.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            
            $('.main-content .container-fluid').prepend(errorAlert);
        }
    });
}

function updateStats(stats) {
    // Atualizar valores nos cards
    Object.keys(stats).forEach(key => {
        const element = document.querySelector(`[data-stat="${key}"]`);
        if (element) {
            if (key.includes('balance') || key.includes('total')) {
                element.textContent = formatCurrency(stats[key]);
            } else {
                element.textContent = stats[key];
            }
        }
    });
}

function changeChartPeriod(days) {
    // Destacar botão ativo
    $('.btn-group .btn').removeClass('active');
    $(`.btn-group .btn[onclick="changeChartPeriod('${days}')"]`).addClass('active');
    
    // Carregar dados para o período
    $.ajax({
        url: '{{ route("dashboard.chart-data") }}',
        type: 'GET',
        data: { 
            type: 'monthly',
            period: days 
        },
        success: function(response) {
            // Atualizar gráfico
            updateFinancialChart(response);
        },
        error: function(xhr, status, error) {
            console.error('Erro ao carregar dados do gráfico:', error);
        }
    });
}

function updateFinancialChart(data) {
    const chart = Chart.getChart('financialChart');
    if (chart) {
        chart.data = data;
        chart.update();
    }
}

function exportDashboard(format) {
    // Redirecionar para a nova rota de exportação
    const url = '/bc/dashboard/export/' + format;
    window.open(url, '_blank');
}

// Função para formatar moeda
function formatCurrency(value) {
    return new Intl.NumberFormat('pt-BR', {
        style: 'currency',
        currency: 'BRL'
    }).format(value);
}

            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return 'R$ ' + value.toLocaleString('pt-BR');
                        }
                    }
                }
            }
        });
}

function initializeCategoryChart() {
    const ctx = document.getElementById('categoryChart').getContext('2d');
    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: ['Alimentação', 'Transporte', 'Educação', 'Saúde', 'Outros'],
            datasets: [{
                data: [30, 25, 20, 15, 10],
                backgroundColor: [
                    '#FF6384',
                    '#36A2EB', 
                    '#FFCE56',
                    '#4BC0C0',
                    '#9966FF'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom'
                }
            }
        });
}

function refreshDashboard() {
    location.reload();
}

function changeChartPeriod(days) {
    // Implementar mudança de período do gráfico
    console.log('Mudando período para:', days, 'dias');
    $('.btn-group .btn').removeClass('active');
    event.target.classList.add('active');
}

function changeSummaryMonth(direction) {
    // Implementar mudança de mês do resumo
    console.log('Mudando mês:', direction);
}

function markAllAsRead() {
    // Implementar marcação de alertas como lidos
    $('#alerts-tab .list-group-item').fadeOut();
}

function dismissAlert(id) {
    // Implementar dismissão de alerta específico
    console.log('Dismissing alert:', id);
}
</script>
@endpush