{% extends "base.html" %}

{% block title %}Território & Mapa — {{ app_name }}{% endblock %}

{% block extra_head %}
<!-- Leaflet MarkerCluster CSS (Design idêntico às imagens de referência) -->
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.5.3/dist/MarkerCluster.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.5.3/dist/MarkerCluster.Default.css" />

<style>
/* Estilização exata das bolhas de cluster verde, amarela e laranja com bordas semi-transparentes */
.marker-cluster-small {
    background-color: rgba(110, 204, 57, 0.6) !important;
    border: 3px solid rgba(110, 204, 57, 0.85) !important;
}
.marker-cluster-small div {
    background-color: transparent !important;
    color: #111827 !important;
    font-weight: 800 !important;
    font-size: 14px !important;
    font-family: Inter, sans-serif !important;
}

.marker-cluster-medium {
    background-color: rgba(241, 211, 87, 0.65) !important;
    border: 3px solid rgba(240, 194, 12, 0.85) !important;
}
.marker-cluster-medium div {
    background-color: transparent !important;
    color: #111827 !important;
    font-weight: 800 !important;
    font-size: 14px !important;
    font-family: Inter, sans-serif !important;
}

.marker-cluster-large {
    background-color: rgba(241, 128, 23, 0.65) !important;
    border: 3px solid rgba(241, 128, 23, 0.85) !important;
}
.marker-cluster-large div {
    background-color: transparent !important;
    color: #111827 !important;
    font-weight: 800 !important;
    font-size: 14px !important;
    font-family: Inter, sans-serif !important;
}

.marker-cluster {
    background-clip: padding-box;
    border-radius: 50% !important;
    width: 46px !important;
    height: 46px !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.25) !important;
}

.marker-cluster div {
    width: 100% !important;
    height: 100% !important;
    margin: 0 !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    text-align: center !important;
}
</style>
{% endblock %}

{% block content %}
<!-- 5 Cards Superiores (Design System v2.4) -->
<div class="kpi-grid" style="grid-template-columns: repeat(5, 1fr);">
    <div class="kpi-card">
        <div class="kpi-icon-box icon-box-blue">👥</div>
        <div>
            <div class="kpi-value">{{ total_geral }}</div>
            <div class="kpi-label">Total Geral</div>
        </div>
    </div>
    
    <div class="kpi-card">
        <div class="kpi-icon-box icon-box-green">⚡</div>
        <div>
            <div class="kpi-value">{{ cadastros_hoje }}</div>
            <div class="kpi-label">Hoje</div>
        </div>
    </div>
    
    <div class="kpi-card">
        <div class="kpi-icon-box icon-box-yellow">📅</div>
        <div>
            <div class="kpi-value">{{ cadastros_mes }}</div>
            <div class="kpi-label">Este Mês</div>
        </div>
    </div>
    
    <div class="kpi-card">
        <div class="kpi-icon-box icon-box-purple">📍</div>
        <div>
            <div class="kpi-value">{{ bairros_cobertos }}</div>
            <div class="kpi-label">Bairros</div>
        </div>
    </div>

    <div class="kpi-card">
        <div class="kpi-icon-box icon-box-red">⚠️</div>
        <div>
            <div class="kpi-value">{{ sem_localizacao }}</div>
            <div class="kpi-label">Sem Localização</div>
        </div>
    </div>
</div>

<!-- Barra de Filtros e Modos de Mapa -->
<div class="content-card" style="padding: 1rem 1.25rem; margin-bottom: 1.25rem;">
    <div style="display: flex; gap: 1rem; align-items: center; flex-wrap: wrap;">
        <div>
            <label style="font-size: 0.75rem; font-weight: 700; color: var(--color-navy-main); display: block;">ZONA / REGIÃO</label>
            <select id="filtroZona" style="padding: 0.5rem; border: 1px solid var(--color-border-subtle); border-radius: 6px; font-size: 0.85rem; font-weight: 600;">
                <option value="">[ Todas as Zonas ]</option>
                {% for z in zonas %}
                    <option value="{{ z }}">{{ z }}</option>
                {% endfor %}
            </select>
        </div>

        <div>
            <label style="font-size: 0.75rem; font-weight: 700; color: var(--color-navy-main); display: block;">CADASTRADOR</label>
            <select id="filtroCadastrador" style="padding: 0.5rem; border: 1px solid var(--color-border-subtle); border-radius: 6px; font-size: 0.85rem;">
                <option value="">[ Todos os Cadastradores ]</option>
                {% for c in cadastradores %}
                    <option value="{{ c.id }}">{{ c.nome }}</option>
                {% endfor %}
            </select>
        </div>

        <div style="margin-left: auto; display: flex; gap: 0.5rem; align-items: center;">
            <span style="font-size: 0.8rem; font-weight: 700; color: var(--color-navy-main);">MODO DE VISUALIZAÇÃO:</span>
            <button id="btnModoCluster" class="btn-primary-orange" style="font-size: 0.8rem; padding: 0.4rem 0.8rem;">
                Agrupamentos (Cluster)
            </button>
        </div>
    </div>
</div>

<!-- Layout Principal Mapa + Sidebars -->
<div style="display: grid; grid-template-columns: 3fr 1fr; gap: 1.5rem;">
    <!-- Container do Mapa Leaflet -->
    <div class="content-card" style="padding: 0; overflow: hidden; height: 600px; position: relative;">
        <div id="mapaLeaflet" style="width: 100%; height: 100%;"></div>
    </div>

    <!-- Sidebars com Cores Oficiais por Zona Urbana -->
    <div style="display: flex; flex-direction: column; gap: 1.25rem;">
        <div class="content-card" style="padding: 1.25rem;">
            <h3 class="section-title-navy" style="font-size: 0.95rem;">📊 Cadastros por Zona</h3>
            <div style="display: flex; flex-direction: column; gap: 0.6rem; margin-top: 0.75rem;">
                {% for z in cadastros_por_zona %}
                <div>
                    <div style="display: flex; justify-content: space-between; font-size: 0.82rem; font-weight: 700;">
                        <span>{{ z.zona }}</span>
                        <span>{{ z.total }}</span>
                    </div>
                    <div class="progress-bar-container" style="height: 8px;">
                        <div class="progress-bar-fill" style="width: {{ (z.total / total_geral * 100) if total_geral > 0 else 0 }}%; background-color: {% if z.zona == 'Zona Leste' %}#FF6500{% elif z.zona == 'Zona Norte' %}#0B0B5C{% elif z.zona == 'Zona Sul' %}#8B5CF6{% elif z.zona == 'Zona Oeste' %}#2563EB{% elif z.zona == 'Centro-Sul' %}#00B884{% else %}#F5B700{% endif %};"></div>
                    </div>
                </div>
                {% else %}
                <span style="font-size: 0.85rem; color: var(--color-text-muted);">Sem dados por zona.</span>
                {% endfor %}
            </div>
        </div>

        <div class="content-card" style="padding: 1.25rem; flex: 1;">
            <h3 class="section-title-navy" style="font-size: 0.95rem;">🏆 Top 10 Bairros</h3>
            <div style="display: flex; flex-direction: column; gap: 0.5rem; margin-top: 0.75rem;">
                {% for b in top_bairros %}
                <div style="display: flex; justify-content: space-between; align-items: center; font-size: 0.82rem; padding: 0.35rem 0; border-bottom: 1px solid var(--color-border-subtle);">
                    <div>
                        <strong style="color: var(--color-navy-main);">{{ loop.index }}. {{ b.bairro }}</strong>
                        <span style="font-size: 0.7rem; color: var(--color-text-muted); display: block;">{{ b.zona }}</span>
                    </div>
                    <span class="badge" style="background: #FFF3E0; color: #FF6500; font-size: 0.8rem; font-weight: 800;">{{ b.total }}</span>
                </div>
                {% else %}
                <span style="font-size: 0.85rem; color: var(--color-text-muted);">Nenhum bairro cadastrado.</span>
                {% endfor %}
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<!-- Leaflet MarkerCluster JS -->
<script src="https://unpkg.com/leaflet.markercluster@1.5.3/dist/leaflet.markercluster.js"></script>

<script>
document.addEventListener('DOMContentLoaded', () => {
    // 1. Inicializar o Mapa Leaflet centrado em Manaus
    const map = L.map('mapaLeaflet').setView([-3.0800, -59.9800], 12);

    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors',
        maxZoom: 19
    }).addTo(map);

    // 2. Inicializar o Leaflet MarkerCluster Group
    let clusterGroup = L.markerClusterGroup({
        chunkedLoading: true,
        showCoverageOnHover: false,
        maxClusterRadius: 50,
        iconCreateFunction: function(cluster) {
            const count = cluster.getChildCount();
            let c = ' marker-cluster-';
            if (count < 10) {
                c += 'small';
            } else if (count < 100) {
                c += 'medium';
            } else {
                c += 'large';
            }
            return new L.DivIcon({
                html: '<div><span>' + count + '</span></div>',
                className: 'marker-cluster' + c,
                iconSize: new L.Point(46, 46)
            });
        }
    });

    map.addLayer(clusterGroup);

    const filtroZona = document.getElementById('filtroZona');
    const filtroCadastrador = document.getElementById('filtroCadastrador');

    async function carregarPontosEClusters() {
        clusterGroup.clearLayers();

        let url = `/territorio/api/pontos?`;
        if (filtroZona.value) url += `&zona=${encodeURIComponent(filtroZona.value)}`;
        if (filtroCadastrador.value) url += `&cadastrador_id=${filtroCadastrador.value}`;

        try {
            const res = await fetch(url, {
                headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest' }
            });
            if (res.status === 401) {
                window.location.href = '/login';
                return;
            }
            const data = await res.json();

            const markersList = [];
            data.pontos.forEach(p => {
                const marker = L.marker([p.lat, p.lng]);
                marker.bindPopup(`
                    <div style="font-family: Inter, sans-serif; padding: 6px; min-width: 190px;">
                        <strong style="color: #123B6D; font-size: 1rem; display: block; margin-bottom: 4px;">👤 ${p.nome}</strong>
                        <div style="font-size: 0.85rem; color: #475569; line-height: 1.4;">
                            📍 Bairro: <strong>${p.bairro}</strong> (${p.zona})<br>
                            🧑‍💼 Multiplicador: <strong>${p.cadastrador}</strong><br>
                            📅 Data: <strong>${p.data}</strong>
                        </div>
                    </div>
                `);
                markersList.push(marker);
            });

            clusterGroup.addLayers(markersList);
            if (markersList.length > 0) {
                map.fitBounds(clusterGroup.getBounds().pad(0.1));
            }
        } catch (e) {
            console.error("Erro ao carregar os pontos do cluster:", e);
        }
    }

    filtroZona.addEventListener('change', carregarPontosEClusters);
    filtroCadastrador.addEventListener('change', carregarPontosEClusters);

    carregarPontosEClusters();
});
</script>
{% endblock %}
