@extends('layouts.admin.theme')

@section('title', env('APP_NAME') . ' :: ' . __("Dashboard Estratégico"))

@section('content')

<style>
    .bg-gradient {
    background: linear-gradient(135deg, #0d6efd, #084298);
}

.ppp-card {
    transition: all 0.3s ease;
    border-radius: 18px;
}

.ppp-card:hover {
    transform: translateY(-6px);
    box-shadow: 0 1.5rem 2rem rgba(0, 0, 0, 0.15);
}

.btn-voltar-ppp {
    background-color: #fff;
    border: 1px solid #dee2e6;
    transition: 0.2s;
}

.btn-voltar-ppp:hover {
    background-color: #f8f9fa;
}

.progress-bar {
    transition: width 0.6s ease-in-out;
}

.search-box {
    position: relative;
    max-width: 500px;
    margin: auto;
}

.search-box input {
    border-radius: 50px;
    padding: 12px 45px 12px 45px;
    border: 1px solid #dee2e6;
    box-shadow: 0 4px 10px rgba(0,0,0,0.05);
    transition: all 0.25s ease;
    font-size: 15px;
}

.search-box input:focus {
    border-color: #0d6efd;
    box-shadow: 0 6px 16px rgba(13,110,253,0.15);
}

.search-box i {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    color: #6c757d;
}

.search-box .search-icon {
    left: 18px;
}

.search-box .clear-icon {
    right: 18px;
    cursor: pointer;
    display: none;
}
</style>

    @php
        $userPermissions = auth()->user()->listaPermissoes();

        // Helper para mapear seções por eixo
        $axisMapping = [
            // Nova aba dedicada à Zeladoria / PCA Digital
            'zeladoria' => ['Serviços e Chamados'],
            // Eixo Atendimento (sem Serviços e Chamados, Comércio e Mobilidade e Transporte)
            'atendimento' => ['Pesquisa de Satisfação'],
            'turismo' => ['Visite Angra', 'Empresas de Turismo', 'Guias Turísticos'],
            'saude' => ['Unidades de Saúde', 'Programa Fibromialgia'],
            'social' => ['Educação', 'Oportunidades'],
            'institucional' => ['Organograma', 'Comunicação', 'SEI! - Pontos Focais']
        ];

        // Função auxiliar para filtrar seções
        $filterSections = function ($sections, $titles) {
            return collect($sections)->filter(function ($section) use ($titles) {
                return in_array($section['title'], $titles);
            });
        };

        $sectionsZeladoria = $filterSections($sections, $axisMapping['zeladoria']);
        $sectionsAtendimento = $filterSections($sections, $axisMapping['atendimento']);
        $sectionsTurismo = $filterSections($sections, $axisMapping['turismo']);
        $sectionsSaude = $filterSections($sections, $axisMapping['saude']);
        $sectionsSocial = $filterSections($sections, $axisMapping['social']);
        $sectionsInstitucional = $filterSections($sections, $axisMapping['institucional']);

        // Coming Soon Mappings
        $comingSoonAtendimento = $filterSections($comingSoonSections ?? [], $axisMapping['atendimento']);
        $comingSoonTurismo = $filterSections($comingSoonSections ?? [], $axisMapping['turismo']);
        $comingSoonSaude = $filterSections($comingSoonSections ?? [], $axisMapping['saude']);
        $comingSoonSocial = $filterSections($comingSoonSections ?? [], $axisMapping['social']);

    @endphp

    <div class="container-fluid py-4 strategic-dashboard">
        <div class="row g-3 mb-4">
            <div class="col-12 d-flex flex-wrap justify-content-between align-items-center gap-3">
                <div>
                    <h1 class="h3 mb-1 fw-bold text-primary">{{ __("Dashboard Estratégico") }}</h1>
                    <p class="text-muted mb-0">{{ __("Prefeitura Municipal de Angra dos Reis") }} •
                        {{ __("Atualizado em") }} {{ $generatedAt->format('d/m/Y H:i') }}</p>
                </div>
                <div class="d-flex gap-2">
                    <button id="fullscreenBtn" class="btn btn-outline-primary btn-sm">
                        <i class="fa-solid fa-expand me-1"></i> {{ __("Tela Cheia") }}
                    </button>
                </div>
            </div>
        </div>

        {{-- Tabs Navigation --}}
        <ul class="nav nav-pills nav-fill mb-4 p-1 bg-white rounded shadow-sm" id="dashboardTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active fw-bold" id="ppps-tab" data-bs-toggle="tab" data-bs-target="#ppps-pane"
                    type="button" role="tab" aria-controls="ppps-pane" aria-selected="true">
                    <i class="fa-solid fa-handshake me-2"></i>{{ __("PPPs e Convênios") }}
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link fw-bold" id="projetos-programas-tab" data-bs-toggle="tab"
                    data-bs-target="#projetos-programas-pane" type="button" role="tab"
                    aria-controls="projetos-programas-pane" aria-selected="false">
                    <i class="fa-solid fa-diagram-project me-2"></i>{{ __("Projetos e Programas") }}
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link fw-bold" id="zeladoria-tab" data-bs-toggle="tab"
                    data-bs-target="#zeladoria-pane" type="button" role="tab" aria-controls="zeladoria-pane"
                    aria-selected="false">
                    <i class="fa-solid fa-broom-ball me-2"></i>{{ __("Zeladoria do Município (PCA Digital)") }}
                </button>
            </li>
            {{-- 
            <li class="nav-item" role="presentation">
                <button class="nav-link fw-bold" id="atendimento-tab" data-bs-toggle="tab"
                    data-bs-target="#atendimento-pane" type="button" role="tab" aria-controls="atendimento-pane"
                    aria-selected="false">
                    <i class="fa-solid fa-headset me-2"></i>{{ __("Atendimento (Conta Angra)") }}
                </button>
            </li>
            --}}
            <li class="nav-item" role="presentation">
                <button class="nav-link fw-bold" id="turismo-tab" data-bs-toggle="tab"
                    data-bs-target="#turismo-pane" type="button" role="tab" aria-controls="turismo-pane"
                    aria-selected="false">
                    <i class="fa-solid fa-umbrella-beach me-2"></i>{{ __("Turismo") }}
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link fw-bold" id="saude-tab" data-bs-toggle="tab"
                    data-bs-target="#saude-pane" type="button" role="tab" aria-controls="saude-pane"
                    aria-selected="false">
                    <i class="fa-solid fa-heart-pulse me-2"></i>{{ __("Saúde") }}
                </button>
            </li>
            {{-- 
            <li class="nav-item" role="presentation">
                <button class="nav-link fw-bold" id="social-tab" data-bs-toggle="tab" data-bs-target="#social-pane"
                    type="button" role="tab" aria-controls="social-pane" aria-selected="false">
                    <i class="fa-solid fa-graduation-cap me-2"></i>{{ __("Social e Educação") }}
                </button>
            </li>
            --}}
            <li class="nav-item" role="presentation">
                <button class="nav-link fw-bold" id="institucional-tab" data-bs-toggle="tab"
                    data-bs-target="#institucional-pane" type="button" role="tab" aria-controls="institucional-pane"
                    aria-selected="false">
                    <i class="fa-solid fa-building-columns me-2"></i>{{ __("Gestão Institucional") }}
                </button>
            </li>
        </ul>

        <div class="tab-content" id="dashboardTabsContent">

            {{-- Tab: PPPs e Convênios --}}
            <div class="tab-pane fade show active" id="ppps-pane" role="tabpanel" aria-labelledby="ppps-tab" tabindex="0">
                @if(isset($pppSummary))
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card shadow-lg border-0 bg-primary overflow-hidden">
                                <div
                                    class="card-header bg-primary text-white border-0 py-4 d-flex justify-content-between align-items-center">
                                    <div class="d-flex align-items-center gap-3">
                                        <div class="bg-white text-primary rounded-circle p-3 shadow-sm">
                                            <i class="{{ $pppSummary['icon'] ?? 'fa-solid fa-handshake' }} fa-2x"></i>
                                        </div>
                                        <div>
                                            <h4 class="mb-0 text-white fw-bold">{{ __($pppSummary['title']) }}</h4>
                                            <small class="text-white-50 fs-6">{{ __($pppSummary['subtitle']) }}</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body p-4">
                                    <div class="row g-4 justify-content-center align-items-center" style="min-height: 100%;">
                                        <div class="col-12">
                                            <div class="row g-2 mb-4">
                                                @foreach ($pppSummary['metrics'] as $metric)
                                                    <div class="col-md-3">
                                                        <div class="card border-0 bg-light h-100">
                                                            <div class="card-body text-center p-4">
                                                                <p class="text-uppercase text-muted fw-bold small mb-2">
                                                                    {{ __($metric['label']) }}</p>
                                                                <h2 class="display-8 fw-bold text-primary mb-0">
                                                                    {{ is_numeric($metric['value']) ? number_format($metric['value'], 0, ',', '.') : $metric['value'] }}
                                                                </h2>
                                                            </div>
                                                        </div>
                                                    </div>
                                                @endforeach
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-8">
                                                <div id="ppp-landing-container" class="row g-5 justify-content-center my-5 pb-5 fade-in">
                                                    <div class="col-6">
                                                        <div class="landing-card teste" onclick="showPppSection('ppp-list-container')">
                                                            <div class="icon-circle">
                                                                <i class="fa-solid fa-handshake"></i>
                                                            </div>
                                                            <h3 class="card-title-custom">Parcerias Público-Privadas</h3>
                                                            <p class="card-text-custom">Acompanhe os projetos de concessão e parcerias estratégicas para o
                                                                desenvolvimento da infraestrutura municipal.</p>
                                                        </div>
                                                    </div>

                                                    <div class="col-6">
                                                        <div class="landing-card" onclick="showPppSection('convenio-list-container')">
                                                            <div class="icon-circle">
                                                                <i class="fa-solid fa-file-contract"></i>
                                                            </div>
                                                            <h3 class="card-title-custom">Convênios e Repasses</h3>
                                                            <p class="card-text-custom">Visualize os convênios federais, estaduais e repasses, garantindo a
                                                                transparência na aplicação dos recursos.</p>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-4 d-flex flex-column justify-content-center">
                                                <h6 class="text-muted text-uppercase fw-bold small mb-4 text-center">
                                                    {{ __("Distribuição da Carteira") }}</h6>
                                                <div style="height: 250px; position: relative;">
                                                    <canvas id="chart-ppp-distribution"></canvas>
                                                </div>
                                                <div class="mt-4 text-center">
                                                    <small class="text-muted d-block mx-auto" style="max-width: 80%;">
                                                        {{ __("Visão consolidada dos ativos de parcerias e convênios gerenciados pela prefeitura.") }}
                                                    </small>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                @endif

                {{-- PPP List Container --}}
                <div id="ppp-list-container" class="d-none fade-in">
                    <div class="convenio-header text-center py-4 mb-4 rounded-4 shadow-sm bg-gradient">
                        <div class="container">
                            <h2 class="display-6 fw-bold mb-2 text-primary">
                                <i class="fa-solid fa-handshake me-2"></i>
                                Parcerias Público-Privadas
                            </h2>
                        </div>
                    </div>

                    <div class="d-flex justify-content-end mb-4">
                        <button class="btn btn-voltar-ppp px-4 py-2 shadow-sm"
                                onclick="showPppSection('ppp-landing-container')">
                            <i class="fa-solid fa-arrow-left me-2"></i>
                            <span>Voltar</span>
                        </button>
                    </div>

                    <div class="search-box mb-4">
                        <i class="fa-solid fa-search search-icon"></i>

                        <input type="text"
                            id="search-ppp"
                            class="form-control"
                            placeholder="Buscar PPP pelo nome, empresa ou valor..."
                            onkeyup="filterCards('search-ppp','ppp-card-item'); toggleClearIcon('search-ppp','clear-ppp')">

                        <i class="fa-solid fa-xmark clear-icon"
                        id="clear-ppp"
                        onclick="clearSearch('search-ppp','ppp-card-item')"></i>
                    </div>

                    <div class="row g-4 pb-5 mb-5">
                        @forelse(collect($pppSummary['highlights'] ?? [])->where('type', 'ppp') as $index => $item)
                            <div class="col-md-6 col-lg-4 ppp-card-item">
                                <div class="card ppp-card border-0 shadow-lg h-100">

                                    @php
                                        $porcentagem_conclusao = (int) ($item['details']['Conclusão (%)'] ?? 0);

                                        if ($porcentagem_conclusao < 40) {
                                            $progressColor = 'bg-danger';
                                        } elseif ($porcentagem_conclusao < 70) {
                                            $progressColor = 'bg-warning';
                                        } else {
                                            $progressColor = 'bg-success';
                                        }

                                        $status = $item['details']['Andamento'] ?? 'Em Análise';

                                        if (str_contains(strtolower($status), 'andamento')) {
                                            $statusColor = 'bg-primary';
                                        } elseif (str_contains(strtolower($status), 'conclu')) {
                                            $statusColor = 'bg-success';
                                        } elseif (str_contains(strtolower($status), 'paralis')) {
                                            $statusColor = 'bg-danger';
                                        } else {
                                            $statusColor = 'bg-secondary';
                                        }
                                    @endphp

                                    <div class="card-body d-flex flex-column">

                                        <!-- STATUS + PRAZO -->
                                        <div class="d-flex justify-content-between align-items-start mb-3">
                                            <span class="badge {{ $statusColor }} px-3 py-2 rounded-pill shadow-sm">
                                                {{ $status }}
                                            </span>

                                            <small class="text-muted text-end">
                                                <i class="fa-regular fa-calendar me-1"></i>
                                                {{ $item['details']['Prazo de Concessão'] ?? 'Prazo n/d' }}
                                            </small>
                                        </div>

                                        <!-- TÍTULO -->
                                        <h5 class="fw-bold text-dark mb-3" style="min-height: 3rem;">
                                            {{ \Illuminate\Support\Str::limit($item['title'], 60) }}
                                        </h5>

                                        <hr class="opacity-25">

                                        <!-- EMPRESA -->
                                        <div class="mb-2">
                                            <div class="small text-uppercase text-muted fw-semibold">
                                                Empresa
                                            </div>
                                            <div class="fw-medium text-truncate">
                                                {{ $item['details']['Empresa'] ?? 'A definir' }}
                                            </div>
                                        </div>

                                        <!-- VALOR -->
                                        <div class="mb-2">
                                            <div class="small text-uppercase text-muted fw-semibold">
                                                Valor Estimado do Contrato
                                            </div>
                                            <div class="fw-medium text-truncate">
                                                {{ $item['details']['Valor Estimado do Contrato'] ?? '-' }}
                                            </div>
                                        </div>

                                        <!-- OBSERVAÇÕES -->
                                        <div class="mb-3">
                                            <div class="small text-uppercase text-muted fw-semibold">
                                                Observações
                                            </div>
                                            <div class="text-muted text-truncate">
                                                {{ $item['details']['Observações'] ?? '-' }}
                                            </div>
                                        </div>

                                        <!-- PROGRESSO -->
                                        <div class="mt-auto">
                                            <div class="d-flex justify-content-between small mb-1">
                                                <span class="fw-semibold text-muted">
                                                    Conclusão do Projeto
                                                </span>
                                                <span class="fw-bold">
                                                    {{ $porcentagem_conclusao }}%
                                                </span>
                                            </div>

                                            <div class="progress rounded-pill shadow-sm" style="height: 12px;">
                                                <div class="progress-bar {{ $progressColor }} rounded-pill"
                                                    role="progressbar"
                                                    style="width: {{ $porcentagem_conclusao }}%"
                                                    aria-valuenow="{{ $porcentagem_conclusao }}"
                                                    aria-valuemin="0"
                                                    aria-valuemax="100">
                                                </div>
                                            </div>
                                        </div>

                                        <!-- BOTÃO -->
                                        <div class="mt-4">
                                            <button class="btn btn-outline-primary w-100 rounded-pill shadow-sm"
                                                    onclick="openPppDetails({{ $loop->index }})">
                                                Ver Detalhes
                                                <i class="fa-solid fa-arrow-right ms-2"></i>
                                            </button>
                                        </div>

                                    </div>
                                </div>
                            </div>

                        @empty
                            <div class="col-12 text-center py-5">
                                <div class="text-muted">
                                    <i class="fa-solid fa-file-circle-xmark fa-3x mb-3 text-secondary"></i>
                                    <h4>Nenhuma PPP encontrada.</h4>
                                </div>
                            </div>
                        @endforelse
                    </div>
                </div>

                {{-- Convenio List Container --}}
                <div id="convenio-list-container" class="d-none fade-in">
                    <div class="convenio-header text-center py-4 mb-4 rounded-4 shadow-sm bg-gradient">
                        <div class="container">
                            <h2 class="display-6 fw-bold mb-2 text-primary">
                                <i class="fa-solid fa-file-contract me-2"></i>
                                Convênios e Repasses
                            </h2>
                        </div>
                    </div>

                    <div class="d-flex justify-content-end mb-4">
                        <button class="btn btn-voltar-ppp px-4 py-2 shadow-sm"
                                onclick="showPppSection('ppp-landing-container')">
                            <i class="fa-solid fa-arrow-left me-2"></i>
                            <span>Voltar</span>
                        </button>
                    </div>

                    <div class="search-box mb-4">
                        <i class="fa-solid fa-search search-icon"></i>

                        <input type="text"
                            id="search-convenio"
                            class="form-control"
                            placeholder="Buscar convênio, concedente ou executor..."
                            onkeyup="filterCards('search-convenio','convenio-card-item'); toggleClearIcon('search-convenio','clear-convenio')">

                        <i class="fa-solid fa-xmark clear-icon"
                        id="clear-convenio"
                        onclick="clearSearch('search-convenio','convenio-card-item')"></i>
                    </div>

                    <div class="row g-4 pb-5 mb-5">
                        @forelse(collect($pppSummary['highlights'] ?? [])->where('type', 'convenio') as $index => $item)
                            <div class="col-md-6 col-lg-4 convenio-card-item">
                                <div class="card ppp-card border-0 shadow-lg h-100">

                                    @php
                                        $porcentagem_conclusao = (int) ($item['details']['Porcentagem'] ?? 0);

                                        if ($porcentagem_conclusao < 40) {
                                            $progressColor = 'bg-danger';
                                        } elseif ($porcentagem_conclusao < 70) {
                                            $progressColor = 'bg-warning';
                                        } else {
                                            $progressColor = 'bg-success';
                                        }

                                        $status = $item['details']['Status / Plataforma'] ?? 'N/A';

                                        if (str_contains(strtolower($status), 'execução') || str_contains(strtolower($status), 'andamento')) {
                                            $statusColor = 'bg-primary';
                                        } elseif (str_contains(strtolower($status), 'conclu')) {
                                            $statusColor = 'bg-success';
                                        } elseif (str_contains(strtolower($status), 'cancel')) {
                                            $statusColor = 'bg-danger';
                                        } else {
                                            $statusColor = 'bg-secondary';
                                        }
                                    @endphp

                                    <div class="card-body d-flex flex-column">

                                        <!-- STATUS + DATA -->
                                        <div class="d-flex justify-content-between align-items-start mb-3">
                                            <span class="badge {{ $statusColor }} px-3 py-2 rounded-pill shadow-sm">
                                                {{ $status }}
                                            </span>

                                            <small class="text-muted text-end">
                                                <i class="fa-regular fa-calendar me-1"></i>
                                                {{ $item['details']['Data'] ?? 'Data n/d' }}
                                            </small>
                                        </div>

                                        <!-- TÍTULO -->
                                        <h5 class="fw-bold text-dark mb-3" style="min-height: 3rem;">
                                            {{ \Illuminate\Support\Str::limit($item['title'], 60) }}
                                        </h5>

                                        <hr class="opacity-25">

                                        <!-- EXECUTOR -->
                                        <div class="mb-2">
                                            <div class="small text-uppercase text-muted fw-semibold">
                                                Executor / Ordenador
                                            </div>
                                            <div class="fw-medium text-truncate">
                                                {{ $item['details']['Executor / Ordenador'] ?? '-' }}
                                            </div>
                                        </div>

                                        <!-- CONCEDENTE -->
                                        <div class="mb-2">
                                            <div class="small text-uppercase text-muted fw-semibold">
                                                Concedente
                                            </div>
                                            <div class="fw-medium text-truncate">
                                                {{ $item['details']['Concedente'] ?? '-' }}
                                            </div>
                                        </div>

                                        <!-- VALORES -->
                                        <div class="row mb-3">
                                            <div class="col-6">
                                                <div class="small text-uppercase text-muted fw-semibold">
                                                    Valor Global
                                                </div>
                                                <div class="fw-bold text-success fs-6 text-truncate">
                                                    {{ $item['details']['Valor Global'] ?? '-' }}
                                                </div>
                                            </div>

                                            <div class="col-6">
                                                <div class="small text-uppercase text-muted fw-semibold">
                                                    Repasse
                                                </div>
                                                <div class="fw-medium text-truncate">
                                                    {{ $item['details']['Repasse'] ?? '-' }}
                                                </div>
                                            </div>
                                        </div>

                                        <!-- PROGRESSO -->
                                        <div class="mt-auto">
                                            <div class="d-flex justify-content-between small mb-1">
                                                <span class="fw-semibold text-muted">
                                                    Conclusão do Projeto
                                                </span>
                                                <span class="fw-bold">
                                                    {{ $porcentagem_conclusao }}%
                                                </span>
                                            </div>

                                            <div class="progress rounded-pill shadow-sm" style="height: 12px;">
                                                <div class="progress-bar {{ $progressColor }} rounded-pill"
                                                    role="progressbar"
                                                    style="width: {{ $porcentagem_conclusao }}%"
                                                    aria-valuenow="{{ $porcentagem_conclusao }}"
                                                    aria-valuemin="0"
                                                    aria-valuemax="100">
                                                </div>
                                            </div>
                                        </div>

                                        <!-- BOTÃO -->
                                        <div class="mt-4">
                                            <button class="btn btn-outline-primary w-100 rounded-pill shadow-sm"
                                                    onclick="openConvenioDetails({{ $loop->index }})">
                                                Ver Detalhes
                                                <i class="fa-solid fa-arrow-right ms-2"></i>
                                            </button>
                                        </div>

                                    </div>
                                </div>
                            </div>
                        @empty
                            <div class="col-12 text-center py-5">
                                <div class="text-muted">
                                    <i class="fa-solid fa-file-circle-xmark fa-3x mb-3 text-secondary"></i>
                                    <h4>Nenhum convênio encontrado.</h4>
                                </div>
                            </div>
                        @endforelse
                    </div>
                </div>

            </div>

            {{-- Tab: Projetos e Programas (mesmas abas do módulo, foco em consulta + priorizar/ordenar) --}}
            <div class="tab-pane fade" id="projetos-programas-pane" role="tabpanel"
                aria-labelledby="projetos-programas-tab" tabindex="0">
                @if(!empty($projetosProgramasDashboardEmbed))
                    @include('admin.projetosProgramas.embedded-dashboard-estrategico', $projetosProgramasDashboardEmbed)
                @else
                    <p class="text-muted small mb-0">{{ __('Conteúdo indisponível para o seu perfil.') }}</p>
                @endif
            </div>

            {{-- Tab: Zeladoria do Município (PCA Digital) --}}
            <div class="tab-pane fade" id="zeladoria-pane" role="tabpanel" aria-labelledby="zeladoria-tab" tabindex="0">
                @php
                    $pca = $pcaDashboard ?? [];
                    $ocorrenciasPorStatus = $pca['ocorrenciasPorStatus'] ?? [];
                    $variacaoAnual = (float) ($pca['variacaoAnual'] ?? 0);
                    $variacaoColor = $variacaoAnual >= 0 ? 'text-success' : 'text-danger';
                    $variacaoIcon = $variacaoAnual >= 0 ? 'fa-arrow-trend-up' : 'fa-arrow-trend-down';
                    $variacaoBg = $variacaoAnual >= 0 ? 'success' : 'danger';
                @endphp

                <!-- Cards Principais de Estatísticas -->
                <div class="row mb-4">
                    <!-- Total -->
                    <div class="col-6 col-md-4 col-xl-2">
                        <div class="card h-100 border-0 shadow-sm border-start border-4 border-primary">
                            <div class="card-body p-3">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <div class="bg-primary-subtle text-primary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                        <i class="fas fa-folder-open"></i>
                                    </div>
                                    <span class="badge bg-primary-subtle text-primary rounded-pill small">Geral</span>
                                </div>
                                <h6 class="text-muted small fw-bold mb-1">{{ __('Total Geral') }}</h6>
                                <h3 class="fw-bold mb-0 text-dark">{{ number_format($pca['totalAberto'] ?? 0, 0, ',', '.') }}</h3>
                            </div>
                        </div>
                    </div>

                    <!-- Hoje -->
                    <div class="col-6 col-md-4 col-xl-2">
                        <div class="card h-100 border-0 shadow-sm border-start border-4 border-info">
                            <div class="card-body p-3">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <div class="bg-info-subtle text-info rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                        <i class="fas fa-calendar-day"></i>
                                    </div>
                                    <span class="badge bg-info-subtle text-info rounded-pill small">Hoje</span>
                                </div>
                                <h6 class="text-muted small fw-bold mb-1">{{ __('Aberto hoje') }}</h6>
                                <h3 class="fw-bold mb-0 text-dark">{{ number_format($pca['quantidadeAbertoHoje'] ?? 0, 0, ',', '.') }}</h3>
                            </div>
                        </div>
                    </div>

                    <!-- Mês -->
                    <div class="col-6 col-md-4 col-xl-2">
                        <div class="card h-100 border-0 shadow-sm border-start border-4 border-success">
                            <div class="card-body p-3">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <div class="bg-success-subtle text-success rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                        <i class="fas fa-calendar-week"></i>
                                    </div>
                                    <span class="badge bg-success-subtle text-success rounded-pill small">Mês</span>
                                </div>
                                <h6 class="text-muted small fw-bold mb-1">{{ __('Este mês') }}</h6>
                                <h3 class="fw-bold mb-0 text-dark">{{ number_format($pca['abertoMesAtual'] ?? 0, 0, ',', '.') }}</h3>
                            </div>
                        </div>
                    </div>

                    <!-- Ano -->
                    <div class="col-6 col-md-4 col-xl-2">
                        <div class="card h-100 border-0 shadow-sm border-start border-4 border-warning">
                            <div class="card-body p-3">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <div class="bg-warning-subtle text-warning rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                        <i class="fas fa-calendar-alt"></i>
                                    </div>
                                    <span class="badge bg-warning-subtle text-warning rounded-pill small">Ano</span>
                                </div>
                                <h6 class="text-muted small fw-bold mb-1">{{ __('Ano atual') }}</h6>
                                <h3 class="fw-bold mb-0 text-dark">{{ number_format($pca['abertoAnoAtual'] ?? 0, 0, ',', '.') }}</h3>
                            </div>
                        </div>
                    </div>

                    <!-- Anterior -->
                    <div class="col-6 col-md-4 col-xl-2">
                        <div class="card h-100 border-0 shadow-sm border-start border-4 border-secondary">
                            <div class="card-body p-3">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <div class="bg-secondary-subtle text-secondary rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                        <i class="fas fa-calendar-check"></i>
                                    </div>
                                    <span class="badge bg-secondary-subtle text-secondary rounded-pill small">Anterior</span>
                                </div>
                                <h6 class="text-muted small fw-bold mb-1">{{ __('Ano passado') }}</h6>
                                <h3 class="fw-bold mb-0 text-dark">{{ number_format($pca['abertoAnoPassado'] ?? 0, 0, ',', '.') }}</h3>
                            </div>
                        </div>
                    </div>

                    <!-- Variação -->
                    <div class="col-6 col-md-4 col-xl-2">
                        <div class="card h-100 border-0 shadow-sm border-start border-4 border-{{ $variacaoBg }}">
                            <div class="card-body p-3">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <div class="bg-{{ $variacaoBg }}-subtle text-{{ $variacaoBg }} rounded-circle d-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">
                                        <i class="fas {{ $variacaoIcon }}"></i>
                                    </div>
                                    <span class="badge bg-{{ $variacaoBg }}-subtle text-{{ $variacaoBg }} rounded-pill small">Var.</span>
                                </div>
                                <h6 class="text-muted small fw-bold mb-1">{{ __('Variação') }}</h6>
                                <h3 class="fw-bold mb-0 {{ $variacaoColor }}">{{ number_format($variacaoAnual, 2) }}%</h3>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Título Secundário -->
                <div class="d-flex align-items-center gap-2 mb-3 mt-5">
                    <div class="bg-primary rounded-pill" style="width: 4px; height: 20px;"></div>
                    <h5 class="mb-0 fw-bold text-dark">{{ __('Status por Categoria') }}</h5>
                </div>

                <!-- Cards de Status -->
                @php
                    $statusConfig = [
                        'ABERTO' => ['color' => 'warning', 'icon' => 'fa-folder-open', 'label' => 'Aberto'],
                        'CONCLUÍDO' => ['color' => 'success', 'icon' => 'fa-check-circle', 'label' => 'Concluído'],
                        'OUVIDORIA' => ['color' => 'info', 'icon' => 'fa-headset', 'label' => 'Ouvidoria'],
                        'SEM ÓRGÃO' => ['color' => 'secondary', 'icon' => 'fa-building', 'label' => 'Sem órgão'],
                        'SENDO AVALIADO' => ['color' => 'primary', 'icon' => 'fa-hourglass-half', 'label' => 'Em Avaliação'],
                        'REPROVADO' => ['color' => 'danger', 'icon' => 'fa-times-circle', 'label' => 'Reprovado'],
                        'MANUTENÇÃO EM ANDAMENTO' => ['color' => 'dark', 'icon' => 'fa-tools', 'label' => 'Em Manutenção'],
                    ];
                @endphp

                <div class="row g-2 mb-5">
                    @foreach ($statusConfig as $status => $config)
                        <div class="col-6 col-md-3 col-xl">
                            <div class="card h-100 border-0 shadow-sm text-center transition-all hover-shadow">
                                <div class="card-body p-3">
                                    <div class="text-{{ $config['color'] }} mb-2 opacity-75">
                                        <i class="fas {{ $config['icon'] }} fa-xl"></i>
                                    </div>
                                    <h6 class="text-muted x-small fw-bold text-uppercase mb-1" style="font-size: 0.65rem; letter-spacing: 0.5px;">{{ __($config['label']) }}</h6>
                                    <h4 class="fw-bold mb-0 text-dark">{{ $ocorrenciasPorStatus[$status] ?? 0 }}</h4>
                                </div>
                            </div>
                        </div>
                    @endforeach
                </div>

                {{-- Gráfico últimos 7 dias + ranking --}}
                <div class="card mb-4 border-0 shadow-sm">
                    <div class="card-header bg-light py-3">
                        <h5 class="mb-0 fw-bold text-primary">
                            <i class="fas fa-chart-area me-2"></i>{{ __('Ocorrências nos últimos 7 dias') }}
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-8">
                                <div class="chart-container" style="height: 300px;">
                                    <canvas id="grafico7Dias"></canvas>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="card h-100 border-0 shadow-sm">
                                    <div class="card-header bg-light py-2">
                                        <h6 class="mb-0 fw-bold">
                                            <i class="fas fa-trophy me-2 text-warning"></i>{{ __('Ranking Últimos 7 dias') }}
                                        </h6>
                                    </div>
                                    <div class="card-body p-0">
                                        <ul class="list-group list-group-flush">
                                            @forelse (($pca['rankingUsuarios'] ?? []) as $index => $item)
                                                <li class="list-group-item d-flex justify-content-between align-items-center py-3">
                                                    <div>
                                                        <span class="badge bg-primary me-2">{{ $index + 1 }}</span>
                                                        {{ $item->name ?? __('Usuário Desconhecido') }}
                                                    </div>
                                                    <span class="badge bg-primary rounded-pill fs-6">{{ $item->total_chamados }}</span>
                                                </li>
                                            @empty
                                                <li class="list-group-item py-3 text-muted">
                                                    {{ __('Nenhuma ocorrência registrada.') }}
                                                </li>
                                            @endforelse
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row g-4 mb-4">
                    {{-- Gráfico mensal --}}
                    <div class="col-12 col-xl-6">
                        <div class="card h-100 border-0 shadow-sm">
                            <div class="card-header bg-light py-3">
                                <h5 class="mb-0 fw-bold text-primary">
                                    <i class="fas fa-calendar-alt me-2"></i>{{ __('Ocorrências Mensais') }}
                                </h5>
                            </div>
                            <div class="card-body">
                                <h6 class="text-center mb-4">
                                    {{ __('Ocorrências por dia em') }}
                                    {{ \Carbon\Carbon::createFromFormat('!m', $pca['mesSelecionado'] ?? now()->month)->locale('pt_BR')->translatedFormat('F') }}/{{ $pca['anoSelecionado'] ?? now()->year }}
                                </h6>
                                <div class="chart-container" style="height: 380px;">
                                    <canvas id="graficoMensal"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>

                    {{-- Gráfico anual --}}
                    <div class="col-12 col-xl-6">
                        <div class="card h-100 border-0 shadow-sm">
                            <div class="card-header bg-light py-3">
                                <h5 class="mb-0 fw-bold text-primary">
                                    <i class="fas fa-chart-bar me-2"></i>{{ __('Ocorrências Anuais') }}
                                </h5>
                            </div>
                            <div class="card-body">
                                <h6 class="text-center mb-4">
                                    {{ __('Ocorrências por mês nos últimos anos') }}
                                </h6>
                                <div class="chart-container" style="height: 380px;">
                                    <canvas id="graficoAnual"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {{-- Variáveis JS para reaproveitar os mesmos gráficos do módulo Ocorrências PCA --}}
                <script>
                    const dadosGrafico7Dias = @json($pca['dadosGrafico7Dias'] ?? []);
                    const dadosGraficoMensal = @json($pca['dadosGraficoMensal'] ?? []);
                    const dadosGraficoAnual = @json($pca['dadosGraficoAnual'] ?? []);
                    const mesesLabels = @json($pca['mesesLabels'] ?? []);
                </script>
            </div>

            {{-- Tab: Atendimento e Serviços (Oculto) --}}
            {{-- 
            <div class="tab-pane fade" id="atendimento-pane" role="tabpanel" aria-labelledby="atendimento-tab" tabindex="0">
                ... (conteúdo comentado) ...
            </div>
            --}}

            {{-- Tab: Turismo --}}
            <div class="tab-pane fade" id="turismo-pane" role="tabpanel" aria-labelledby="turismo-tab" tabindex="0">
                <div class="row g-4">
                    @foreach ($sectionsTurismo as $section)
                        @include('admin.dashboard-estrategico.partials._section_card', ['section' => $section, 'userPermissions' => $userPermissions])
                    @endforeach
                    @foreach ($comingSoonTurismo as $mock)
                        @include('admin.dashboard-estrategico.partials._coming_soon_card', ['mock' => $mock])
                    @endforeach
                </div>
            </div>

            {{-- Tab: Saúde --}}
            <div class="tab-pane fade" id="saude-pane" role="tabpanel" aria-labelledby="saude-tab" tabindex="0">
                <div class="row g-4">
                    {{-- Card: Programa Fibromialgia --}}
                    @php
                        $fibroSection = $sectionsSaude->where('title', 'Programa Fibromialgia')->first();
                    @endphp
                    @if($fibroSection)
                    <div class="col-12 col-xl-8">
                        <div class="card shadow-sm h-100">
                            <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                                <div class="d-flex align-items-center gap-3">
                                    <span class="badge text-bg-primary rounded-circle p-3">
                                        <i class="{{ $fibroSection['icon'] ?? 'fa-solid fa-notes-medical' }}"></i>
                                    </span>
                                    <div>
                                        <h5 class="mb-0">{{ __($fibroSection['title']) }}</h5>
                                        <small class="text-muted">{{ __($fibroSection['subtitle']) }}</small>
                                    </div>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="row g-4">
                                    <div class="col-md-5">
                                        <div class="row g-2">
                                            @foreach ($fibroSection['metrics'] as $metric)
                                            <div class="col-12">
                                                <div class="border rounded-3 p-3 bg-light">
                                                    <p class="text-muted small mb-1">{{ __($metric['label']) }}</p>
                                                    <p class="h3 fw-semibold mb-0">
                                                        {{ number_format((int) ($metric['value'] ?? 0), 0, ',', '.') }}
                                                    </p>
                                                </div>
                                            </div>
                                            @endforeach
                                        </div>
                                    </div>
                                    <div class="col-md-7 border-start">
                                        <div class="text-center mb-3">
                                            <h6 class="fw-bold text-muted small">{{ __("Situação das Carteirinhas") }}</h6>
                                        </div>
                                        <div style="height: 300px;">
                                            <canvas id="chart-fibro"></canvas>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    @endif

                    {{-- Card: Unidades de Saúde --}}
                    @php
                        $unidadeSection = $sectionsSaude->where('title', 'Unidades de Saúde')->first();
                    @endphp
                    @if($unidadeSection)
                    <div class="col-12 col-xl-4">
                        <div class="card shadow-sm h-100">
                            <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                                <div class="d-flex align-items-center gap-3">
                                    <span class="badge text-bg-primary rounded-circle p-3">
                                        <i class="{{ $unidadeSection['icon'] ?? 'fa-solid fa-hospital' }}"></i>
                                    </span>
                                    <div>
                                        <h5 class="mb-0">{{ __($unidadeSection['title']) }}</h5>
                                        <small class="text-muted">{{ __($unidadeSection['subtitle']) }}</small>
                                    </div>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="row g-2">
                                    @foreach ($unidadeSection['metrics'] as $metric)
                                    <div class="col-12">
                                        <div class="border rounded-3 p-3 bg-light text-center">
                                            <p class="text-muted small mb-1">{{ __($metric['label']) }}</p>
                                            <p class="display-6 fw-semibold mb-0">
                                                {{ number_format((int) ($metric['value'] ?? 0), 0, ',', '.') }}
                                            </p>
                                        </div>
                                    </div>
                                    @endforeach
                                </div>
                            </div>
                        </div>
                    </div>
                    @endif

                    @foreach ($comingSoonSaude as $mock)
                        @include('admin.dashboard-estrategico.partials._coming_soon_card', ['mock' => $mock])
                    @endforeach
                </div>
            </div>

            {{-- Tab: Social e Educação (Oculto) --}}
            {{-- 
            <div class="tab-pane fade" id="social-pane" role="tabpanel" aria-labelledby="social-tab" tabindex="0">
                ... (conteúdo comentado) ...
            </div>
            --}}

            {{-- Tab: Gestão Institucional --}}
            <div class="tab-pane fade" id="institucional-pane" role="tabpanel" aria-labelledby="institucional-tab"
                tabindex="0">
                <div class="row g-4">
                    {{-- Card de Gráfico: Produção de Comunicação --}}
                    <div class="col-12 col-xl-6">
                        <div class="card h-100 shadow-sm">
                            <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
                                <div>
                                    <h5 class="mb-0">{{ __("Produção de Comunicação") }}</h5>
                                    <small class="text-muted">{{ __("Notícias x Boletins") }}</small>
                                </div>
                                <span class="badge bg-info-subtle text-info">
                                    <i class="fa-solid fa-newspaper"></i>
                                </span>
                            </div>
                            <div class="card-body">
                                <div class="chart-container" style="height: 350px;">
                                    <canvas id="chart-communication"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>

                    {{-- Cards de Seção: Organograma, Comunicação, SEI --}}
                    @foreach ($sectionsInstitucional as $section)
                        @include('admin.dashboard-estrategico.partials._section_card', ['section' => $section, 'userPermissions' => $userPermissions])
                    @endforeach
                </div>
            </div>
        </div>
    </div>

    @push('after-scripts')
        {{-- Modal Detalhes PPP --}}
        <div class="modal fade" id="pppDetailsModal" tabindex="-1" aria-labelledby="pppDetailsModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl modal-dialog-centered">
                <div class="modal-content border-0 rounded-4 overflow-hidden shadow-lg">

                    <div class="convenio-header">
                        <div class="container-fluid px-4">
                            <h4 class="fw-bold mb-1 text-white" id="pppDetailsModalLabel">
                                Detalhes da PPP
                            </h4>
                            <p class="opacity-75 mb-0 text-white" id="pppMetaInfo">
                                Informações da Parceria Público-Privada
                            </p>
                        </div>
                    </div>

                    <div class="modal-body p-4 bg-light">
                        <div id="pppDetailsContent">
                            <!-- Conteúdo via JS -->
                        </div>
                    </div>

                    <div class="modal-footer bg-white border-0 px-4 pb-4">
                        <button type="button" class="btn btn-outline-secondary px-4" data-bs-dismiss="modal">
                            Fechar
                        </button>
                    </div>

                </div>
            </div>
        </div>

        {{-- Modal Detalhes Convênio --}}
        <div class="modal fade" id="convenioDetailsModal" tabindex="-1" aria-labelledby="convenioDetailsModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-xl modal-dialog-centered">
                <div class="modal-content border-0 rounded-4 overflow-hidden shadow-lg">

                    <div class="convenio-header">
                        <div class="container-fluid px-4">
                            <h4 class="fw-bold mb-1 text-white" id="convenioDetailsModalLabel">
                                Detalhes do Convênio
                            </h4>
                            <p class="opacity-75 mb-0 text-white" id="convenioPropostaId">
                                Proposta ID: -
                            </p>
                        </div>
                    </div>

                    <div class="modal-body p-4 bg-light">
                        <div id="convenioDetailsContent">
                            <!-- Conteúdo via JS -->
                        </div>
                    </div>

                    <div class="modal-footer bg-white border-0 px-4 pb-4">
                        <button type="button" class="btn btn-outline-secondary px-4" data-bs-dismiss="modal">
                            Fechar
                        </button>
                    </div>

                </div>
            </div>
        </div>

        <script>
            window.dashboardEstrategicoPayload = @json($chartPayload);
            window.pppItems = @json(
                collect($pppSummary['highlights'] ?? [])
                    ->where('type', 'ppp')
                    ->values()
            );

            window.convenioItems = @json(
                collect($pppSummary['highlights'] ?? [])
                    ->where('type', 'convenio')
                    ->values()
            );

            function filterPppList(type) {
                document.querySelectorAll('.btn-group .btn').forEach(btn => btn.classList.remove('active'));
                if (type === 'all') document.getElementById('btn-show-all').classList.add('active');
                if (type === 'ppp') document.getElementById('btn-show-ppps').classList.add('active');
                if (type === 'convenio') document.getElementById('btn-show-convenios').classList.add('active');

                const items = document.querySelectorAll('.ppp-item');
                items.forEach(item => {
                    if (type === 'all' || item.dataset.type === type) {
                        item.classList.remove('d-none');
                        item.classList.add('d-flex');
                    } else {
                        item.classList.add('d-none');
                        item.classList.remove('d-flex');
                    }
                });
            }

            function openPppDetails(index) {

                const item = window.pppItems[index];

                if (!item) {
                    console.error('PPP Item not found:', index);
                    return;
                }

                const modalLabel = document.getElementById('pppDetailsModalLabel');
                const modalContent = document.getElementById('pppDetailsContent');

                modalLabel.textContent = 'Detalhes da Parceria Público-Privada';

                const d = item.details || {};

                let leftFields = '';
                let rightFields = '';

                let entries = Object.entries(d);
                let half = Math.ceil(entries.length / 2);

                entries.forEach(([key, value], index) => {
                    const field = `
                        <div class="col-md-6">
                            <div class="detail-label-modal">${key}</div>
                            <div class="detail-value-modal">
                                ${value || 'Não informado'}
                            </div>
                        </div>
                    `;

                    if (index < half) {
                        leftFields += field;
                    } else {
                        rightFields += field;
                    }
                });

                let historicosHtml = '';
                if (item.historicos && item.historicos.length > 0) {
                    let timelineItems = item.historicos.map(h => `
                        <div class="mb-3 position-relative" style="padding-left: 15px; border-left: 2px solid #0d6efd;">
                            <span class="position-absolute" style="left: -7px; top: 0; background: #fff; border: 2px solid #0d6efd; border-radius: 50%; width: 12px; height: 12px;"></span>
                            
                            <div class="fw-bold text-primary" style="font-size: 0.9rem;">
                                ${h.orgao || 'Órgão não informado'}
                            </div>

                            <div class="text-muted" style="font-size: 0.75rem;">
                                <i class="fa-regular fa-calendar-days me-1"></i>
                                ${h.data_fim ? `${h.data} → ${h.data_fim}` : h.data}
                            </div>

                            ${h.observacao ? `
                                <div class="mt-1 text-dark bg-white p-2 rounded border" style="font-size: 0.85rem;">
                                    ${h.observacao}
                                </div>
                            ` : ''}
                        </div>
                    `).join('');

                    historicosHtml = `
                        <div class="card detail-card-modal p-4 mb-4 bg-light border-0">
                            <div class="detail-section-title-modal">
                                <i class="fa-solid fa-clock-rotate-left me-2"></i>
                                Histórico de Tramitação
                            </div>
                            <div class="mt-2">
                                ${timelineItems}
                            </div>
                        </div>
                    `;
                }

                const pdfUrl = `{{ route('admin.dashboardEstrategico.exportPpp', ['id' => 'ITEM_ID', 'type' => 'pdf']) }}`.replace('ITEM_ID', item.id);
                const xlsxUrl = `{{ route('admin.dashboardEstrategico.exportPpp', ['id' => 'ITEM_ID', 'type' => 'xlsx']) }}`.replace('ITEM_ID', item.id);
                const csvUrl = `{{ route('admin.dashboardEstrategico.exportPpp', ['id' => 'ITEM_ID', 'type' => 'csv']) }}`.replace('ITEM_ID', item.id);

                let html = `
                    <div class="container-fluid">
                        <div class="row">
                            
                            <div class="col-lg-8">

                                <div class="card detail-card-modal p-4 mb-4">
                                    <div class="d-flex justify-content-between align-items-start">
                                        <div class="detail-section-title-modal text-primary">
                                            <i class="fa-solid fa-file-contract me-2"></i>
                                            Informações Gerais
                                        </div>
                                        <div class="btn-group btn-group-sm rounded shadow-sm">
                                            <a href="${pdfUrl}" target="_blank" class="btn btn-danger text-white"><i class="fa-solid fa-file-pdf"></i> .PDF</a>
                                            <a href="${csvUrl}" class="btn btn-secondary text-white"><i class="fa-solid fa-file-csv"></i> .CSV</a>
                                        </div>
                                    </div>

                                    <p class="fs-5 text-dark mt-3 mb-4 fw-bold">
                                        ${item.title || '-'}
                                    </p>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="detail-label-modal">Status</div>
                                            <div class="detail-value-modal">
                                                <span class="badge bg-${item.status_class}">
                                                    ${item.status}
                                                </span>
                                            </div>
                                        </div>

                                        <div class="col-md-6">
                                            <div class="detail-label-modal">Meta</div>
                                            <div class="detail-value-modal">
                                                ${item.meta || '-'}
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <div class="card detail-card-modal p-4 mb-4">
                                    <div class="detail-section-title-modal">
                                        <i class="fa-solid fa-circle-info me-2"></i>
                                        Detalhamento
                                    </div>

                                    <div class="row">
                                        ${leftFields}
                                    </div>
                                </div>

                            </div>

                            <div class="col-lg-4">

                                <div class="card detail-card-modal p-4 mb-4 bg-light border-0">
                                    <div class="detail-section-title-modal">
                                        <i class="fa-solid fa-diagram-project me-2"></i>
                                        Informações Complementares
                                    </div>

                                    <div class="row">
                                        ${rightFields}
                                    </div>
                                </div>

                            </div>

                        </div>
                        
                        <div class="row">
                            <div class="col-12">
                                ${historicosHtml}
                            </div>
                        </div>
                    </div>
                `;

                modalContent.innerHTML = html;

                const modal = new bootstrap.Modal(
                    document.getElementById('pppDetailsModal')
                );

                modal.show();
            }

            function openConvenioDetails(index) {

                const item = window.convenioItems[index];

                if (!item) {
                    console.error('Convênio não encontrado:', index);
                    return;
                }

                const d = item.details || {};

                document.getElementById('convenioPropostaId').textContent =
                    item.meta || 'Convênio';

                let html = `
                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-lg-8">

                                <div class="card detail-card-modal p-4 mb-4">
                                    <div class="detail-section-title-modal">
                                        <i class="fa-solid fa-file-contract me-2"></i>
                                        Identificação
                                    </div>

                                    <p class="fs-5 text-dark mb-4">
                                        ${d["Objeto"] || '-'}
                                    </p>

                                    <div class="row">
                                        ${generateField("Executor / Ordenador", d["Executor / Ordenador"])}
                                        ${generateField("Concedente", d["Concedente"])}
                                        ${generateField("Local", d["Local"])}
                                        ${generateField("Status", item.status)}
                                    </div>
                                </div>

                                <div class="card detail-card-modal p-4 mb-4">
                                    <div class="detail-section-title-modal">
                                        <i class="fa-solid fa-diagram-project me-2"></i>
                                        Informações do Programa
                                    </div>

                                    <div class="row">
                                        ${generateField("Status / Plataforma", d["Status / Plataforma"])}
                                        ${generateField("Programa", d["Programa"])}
                                        ${generateField("Programa Nº PAC", d["Programa Nº PAC"])}
                                        ${generateField("Tipo de Programa", d["Tipo de Programa"])}
                                        ${generateField("Proposta ID Nº", d["Proposta ID Nº"])}
                                    </div>
                                </div>

                                <div class="card detail-card-modal p-4 mb-4">
                                    <div class="detail-section-title-modal">
                                        <i class="fa-solid fa-calendar-days me-2"></i>
                                        Prazos
                                    </div>

                                    <div class="row">
                                        ${generateField("Prazo de Cadastro", d["Prazo de Cadastro"])}
                                        ${generateField("Data", d["Data"])}
                                        ${generateField("Prazo de Execução (Meses)", d["Prazo de Execução (Meses)"])}
                                    </div>
                                </div>

                            </div>

                            <div class="col-lg-4">

                                <div class="card detail-card-modal p-4 mb-4 bg-light border-0">
                                    <div class="detail-section-title-modal">
                                        <i class="fa-solid fa-coins me-2"></i>
                                        Valores Financeiros
                                    </div>

                                    <div class="detail-label-modal">Valor Global</div>
                                    <div class="detail-value-modal value-highlight-modal text-success">
                                        ${d["Valor Global"] || '-'}
                                    </div>

                                    <hr>

                                    ${generateFieldSimple("Repasse", d["Repasse"])}
                                    ${generateFieldSimple("Contrapartida", d["Contrapartida"])}
                                </div>

                                <div class="card detail-card-modal p-4 mb-4">
                                    <div class="detail-section-title-modal">
                                        <i class="fa-solid fa-circle-info me-2"></i>
                                        Informações Complementares
                                    </div>

                                    ${generateFieldFull("ID do Convênio", item.id)}
                                </div>

                            </div>
                        </div>
                    </div>
                `;

                document.getElementById('convenioDetailsContent').innerHTML = html;

                const modal = new bootstrap.Modal(
                    document.getElementById('convenioDetailsModal')
                );

                modal.show();
            }

            function generateField(label, value) {
                return `
                    <div class="col-md-6">
                        <div class="detail-label-modal">${label}</div>
                        <div class="detail-value-modal">${value || '-'}</div>
                    </div>
                `;
            }

            function generateFieldFull(label, value) {
                return `
                    <div class="col-md-12">
                        <div class="detail-label-modal">${label}</div>
                        <div class="detail-value-modal">${value || '-'}</div>
                    </div>
                `;
            }

            function generateFieldSimple(label, value) {
                return `
                    <div class="detail-label-modal">${label}</div>
                    <div class="detail-value-modal fw-bold">${value || '-'}</div>
                `;
            }

            function filterCards(inputId, cardClass) {
                let input = document.getElementById(inputId);
                let filter = input.value.toLowerCase();
                let cards = document.getElementsByClassName(cardClass);

                for (let i = 0; i < cards.length; i++) {

                    let card = cards[i];
                    let text = card.innerText.toLowerCase();

                    if (text.includes(filter)) {
                        card.style.display = "";
                    } else {
                        card.style.display = "none";
                    }
                }
            }

            function toggleClearIcon(inputId, iconId) {

                let input = document.getElementById(inputId);
                let icon = document.getElementById(iconId);

                if (input.value.length > 0) {
                    icon.style.display = "block";
                } else {
                    icon.style.display = "none";
                }
            }

            function clearSearch(inputId, cardClass) {

                let input = document.getElementById(inputId);
                input.value = "";

                filterCards(inputId, cardClass);

                let icon = document.querySelector(`#${inputId} ~ .clear-icon`);
                if (icon) icon.style.display = "none";
            }

            function showPppSection(sectionId) {
                // Não esconder mais os cartões de opções quando clicar
                // document.getElementById('ppp-landing-container').classList.add('d-none');
                
                document.getElementById('ppp-list-container').classList.add('d-none');
                document.getElementById('convenio-list-container').classList.add('d-none');

                if (sectionId === 'ppp-landing-container') {
                    // Apenas recolhe as listas, voltando ao estado inicial
                    const landing = document.getElementById('ppp-landing-container');
                    if (landing) {
                        landing.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }
                    return;
                }

                const section = document.getElementById(sectionId);
                if (section) {
                    section.classList.remove('d-none');
                    // Aguarda um instante para a div ficar renderizada antes de aplicar o scroll
                    setTimeout(() => {
                        section.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }, 150);
                }
            }
        </script>
        <script src="{{ asset('pmar/js/dashboard-estrategico.js') }}"></script>
        <script src="{{ asset('pmar/js/dashboard-estrategico-fullscreen.js') }}"></script>
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                var params = new URLSearchParams(window.location.search);
                if (params.has('pp_subtab')) {
                    var trigger = document.getElementById('projetos-programas-tab');
                    if (trigger && typeof bootstrap !== 'undefined' && bootstrap.Tab) {
                        bootstrap.Tab.getOrCreateInstance(trigger).show();
                    }
                }
            });
        </script>
    @endpush
@endsection