{% extends 'app_base.html.twig' %}

{% block title %}Scan Inventaire — Tableau de bord{% endblock %}

{% set statusLabels = {'en_cours': 'En cours', 'a_valider': 'À valider', 'valide': 'Validés', 'annule': 'Annulés'} %}
{% set statusColors = {
    'en_cours':  {bg: 'bg-blue-50',  text: 'text-blue-700',  border: 'border-blue-200'},
    'a_valider': {bg: 'bg-amber-50', text: 'text-amber-700', border: 'border-amber-200'},
    'valide':    {bg: 'bg-green-50', text: 'text-green-700', border: 'border-green-200'},
    'annule':    {bg: 'bg-gray-100', text: 'text-gray-600',  border: 'border-gray-200'},
} %}
{% set palette = {
    'en_cours': '#3B82F6', 'a_valider': '#F59E0B', 'valide': '#22C55E', 'annule': '#9CA3AF',
    'brand': '#21409A'
} %}

{% set monthlyChart = {
    chart: { type: 'bar', stacked: true, height: 280, toolbar: { show: false }, fontFamily: 'inherit',
             animations: { enabled: true, easing: 'easeinout', speed: 600 } },
    series: [
        { name: 'En cours',  data: byMonthStatus.en_cours },
        { name: 'À valider', data: byMonthStatus.a_valider },
        { name: 'Validés',   data: byMonthStatus.valide },
        { name: 'Annulés',   data: byMonthStatus.annule }
    ],
    xaxis: { categories: monthsLabels, labels: { style: { colors: '#94a3b8', fontSize: '11px' } },
             axisBorder: { show: false }, axisTicks: { show: false } },
    yaxis: { labels: { style: { colors: '#94a3b8', fontSize: '11px' } } },
    plotOptions: { bar: { borderRadius: 4, columnWidth: '60%', borderRadiusApplication: 'end' } },
    colors: [palette.en_cours, palette.a_valider, palette.valide, palette.annule],
    fill: { opacity: 1 },
    legend: { position: 'top', horizontalAlign: 'right', labels: { colors: '#475569' }, markers: { width: 10, height: 10, radius: 10 } },
    dataLabels: { enabled: false },
    grid: { borderColor: '#f1f5f9', strokeDashArray: 3, padding: { left: 4, right: 4 } },
    tooltip: { theme: 'light' }
} %}

{% set topConcessionsValues = [] %}
{% for v in topConcessions %}{% set topConcessionsValues = topConcessionsValues|merge([v]) %}{% endfor %}
{% set topConcessionsChart = {
    chart: { type: 'bar', height: max(220, topConcessions|length * 36), toolbar: { show: false }, fontFamily: 'inherit' },
    series: [{ name: 'Inventaires', data: topConcessionsValues }],
    xaxis: { categories: topConcessions|keys, labels: { style: { colors: '#94a3b8', fontSize: '12px' } },
             axisBorder: { show: false }, axisTicks: { show: false } },
    yaxis: { labels: { style: { colors: '#475569', fontSize: '12px' } } },
    plotOptions: { bar: { horizontal: true, borderRadius: 4, barHeight: '60%', distributed: true } },
    colors: ['#21409A', '#2B4FB5', '#3B5BC0', '#5570CB', '#6E85D6', '#8A9CE0', '#A8B6EA', '#C7D0F3'],
    dataLabels: { enabled: true, textAnchor: 'start', offsetX: 8,
                  style: { colors: ['#0f172a'], fontSize: '12px', fontWeight: 600 } },
    legend: { show: false },
    grid: { borderColor: '#f1f5f9', strokeDashArray: 3 },
    tooltip: { theme: 'light' }
} %}

{% block content %}
<div class="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6">

    {# ─── Bandeau scan (full width, compact) — masqué pour les groupes sans droit de création (LECTEUR) ─── #}
    {% if is_granted('SCAN_CREATE') %}
    <a href="{{ path('app_scan') }}" class="group flex items-center gap-4 px-6 py-4 bg-red-brand text-white rounded-2xl hover:bg-red-brand-dark hover:shadow-red-glow transition-all active:scale-[0.99] focus:outline-none focus:ring-2 focus:ring-red-brand focus:ring-offset-2 focus:ring-offset-white">
        <div class="w-10 h-10 bg-white/15 rounded-xl flex items-center justify-center shrink-0">
            <svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                <path stroke-linecap="round" stroke-linejoin="round" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
                <path stroke-linecap="round" stroke-linejoin="round" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
        </div>
        <div class="flex-1 min-w-0">
            <p class="font-semibold text-base leading-tight">Démarrer un scan</p>
            <p class="text-xs text-white/80 mt-0.5">Photos plaque & VIN par paires</p>
        </div>
        <svg class="w-5 h-5 group-hover:translate-x-1 transition-transform shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
            <path stroke-linecap="round" stroke-linejoin="round" d="M13 7l5 5m0 0l-5 5m5-5H6" />
        </svg>
    </a>
    {% endif %}

    {# ─── 5 KPI en ligne ─── #}
    <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3">
        <div class="bg-white border border-gray-200 rounded-2xl p-4 shadow-sm">
            <p class="text-xs text-gray-500 uppercase tracking-wide">Inventaires {{ year }}</p>
            <p class="text-2xl font-display font-bold text-gray-900 mt-1">{{ stats.sessions }}</p>
        </div>
        <div class="bg-white border border-gray-200 rounded-2xl p-4 shadow-sm">
            <p class="text-xs text-gray-500 uppercase tracking-wide">Véhicules</p>
            <p class="text-2xl font-display font-bold text-gray-900 mt-1">{{ stats.vehicles }}</p>
        </div>
        <a href="{{ path('app_inventaires', {status: 'en_cours'}) }}" class="bg-blue-50 border border-blue-200 rounded-2xl p-4 hover:shadow-sm transition-shadow">
            <p class="text-xs text-blue-700 uppercase tracking-wide">En cours</p>
            <p class="text-2xl font-display font-bold text-blue-700 mt-1">{{ byStatus['en_cours'] ?? 0 }}</p>
        </a>
        <a href="{{ path('app_inventaires', {status: 'a_valider'}) }}" class="bg-amber-50 border border-amber-200 rounded-2xl p-4 hover:shadow-sm transition-shadow">
            <p class="text-xs text-amber-700 uppercase tracking-wide">À valider</p>
            <p class="text-2xl font-display font-bold text-amber-700 mt-1">{{ byStatus['a_valider'] ?? 0 }}</p>
        </a>
        <div class="bg-white border border-gray-200 rounded-2xl p-4 shadow-sm">
            <p class="text-xs text-gray-500 uppercase tracking-wide">Dernier scan</p>
            {% if stats.lastAt %}
                <p class="text-base font-display font-bold text-gray-900 mt-1">{{ stats.lastAt|date('d/m') }}</p>
                <p class="text-xs text-gray-400">{{ stats.lastAt|date('H:i') }}</p>
            {% else %}
                <p class="text-base font-display font-bold text-gray-300 mt-1">—</p>
            {% endif %}
        </div>
    </div>

    {# ─── Inventaires par mois (barres empilées par statut) ─── #}
    <div class="bg-white border border-gray-200 rounded-2xl p-5 shadow-sm">
        <h2 class="text-sm font-semibold text-gray-900 uppercase tracking-wide mb-4">Inventaires par mois</h2>
        {% if stats.sessions == 0 %}
            <div class="h-60 flex items-center justify-center text-sm text-gray-400">Aucun inventaire enregistré pour {{ year }}.</div>
        {% else %}
            <div data-controller="chart" data-chart-options-value='{{ monthlyChart|json_encode|e('html_attr') }}'></div>
        {% endif %}
    </div>

    {# ─── Top concessions ─── #}
    <div class="bg-white border border-gray-200 rounded-2xl p-5 shadow-sm">
        <h2 class="text-sm font-semibold text-gray-900 uppercase tracking-wide mb-1">Top concessions</h2>
        <p class="text-xs text-gray-400 mb-4">Nombre d'inventaires par concession en {{ year }}.</p>
        {% if topConcessions|length == 0 %}
            <p class="text-sm text-gray-400 text-center py-8">Aucune concession identifiée.</p>
        {% else %}
            <div data-controller="chart" data-chart-options-value='{{ topConcessionsChart|json_encode|e('html_attr') }}'></div>
        {% endif %}
    </div>

    {# ─── Derniers scans ─── #}
    <div class="bg-white border border-gray-200 rounded-2xl p-6 shadow-sm">
        <div class="flex items-center justify-between mb-4">
            <h2 class="text-sm font-semibold text-gray-900 uppercase tracking-wide">Derniers scans</h2>
            <a href="{{ path('app_inventaires') }}" class="text-xs text-gray-500 hover:text-red-brand transition-colors">Tout voir →</a>
        </div>
        {% if recent|length == 0 %}
            <p class="text-sm text-gray-400 text-center py-8">Aucun scan</p>
        {% else %}
            <ul class="divide-y divide-gray-100">
                {% for s in recent %}
                    {% set c = statusColors[s.status] %}
                    <li class="py-3 first:pt-0 last:pb-0">
                        <a href="{{ path('app_inventaire_detail', {id: s.id}) }}" class="flex items-center justify-between gap-3 hover:bg-gray-50 -mx-2 px-2 py-1 rounded-lg transition-colors">
                            <div class="min-w-0 flex-1">
                                <div class="flex items-center gap-2 mb-0.5">
                                    <span class="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium border {{ c.bg }} {{ c.text }} {{ c.border }}">{{ statusLabels[s.status] }}</span>
                                    <span class="text-sm font-medium text-gray-900 truncate">{{ s.label }}</span>
                                </div>
                                <p class="text-xs text-gray-500">
                                    {{ s.count }} véh.
                                    · par <span class="text-gray-700">{{ s.userEmail }}</span>
                                    {% if s.locationNote %} · 📍 {{ s.locationNote }}{% endif %}
                                </p>
                                {% if s.concessions|length > 0 %}
                                    <p class="text-xs text-gray-500 mt-0.5 truncate">🏢 {{ s.concessions|concession_names|join(' · ') }}</p>
                                {% endif %}
                            </div>
                            <svg class="w-4 h-4 text-gray-300 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" />
                            </svg>
                        </a>
                    </li>
                {% endfor %}
            </ul>
        {% endif %}
    </div>
</div>
{% endblock %}
