{% extends "base.html" %}
{% load static i18n %}

{% block title %}{% trans "Recruitment Dashboard" %} - {{ block.super }}{% endblock %}

{% block customCSS %}
<style>
    /* UI Variables for the KAAT-S Theme (Teal/Consistent Look) */
    :root {
        --kaauh-teal: #00636e; /* Dark Teal */
        --kaauh-teal-light: #0093a3;
        --kaauh-teal-dark: #004a53;
        --kaauh-border: #eaeff3;
        --kaauh-primary-text: #343a40;
        --color-success: #28a745;
        --color-warning: #ffc107; /* Standardized warning color */
        --color-info: #17a2b8;
    }

    /* General Card Styling */
    .card {
        border: 1px solid var(--kaauh-border);
        border-radius: 0.75rem;
        box-shadow: 0 4px 12px rgba(0,0,0,0.06);
        transition: transform 0.2s, box-shadow 0.2s;
        background-color: white;
    }
    .card:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(0,0,0,0.1);
    }

    /* ------------------------------------------------------------- */
    /* CONSOLIDATED CARD HEADER STYLES (for both main and stat cards)*/
    /* ------------------------------------------------------------- */
    .card-header {
        font-weight: 600;
        /* Consistent, reduced padding for compact look */
        padding: 0.5rem 0.75rem; 
        border-bottom: 1px solid var(--kaauh-border);
        background-color: #f8f9fa;
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: auto; 
    }

    /* Target h2 (for main headers) and h3 (for stat card headers) */
    .card-header h1, .card-header h2, .card-header h3, .card-header h6 {
        display: flex;
        align-items: center;
        color: var(--kaauh-primary-text);
        margin: 0;
        
        /* Font size for MAIN card titles (e.g., "Data Scope: All Jobs") */
        font-size: 1.25rem; 
        font-weight: 600;
    }

    /* Override for H3 inside stat cards to make them very small */
    .stats .card-header h3 {
        font-size: 0.85rem; /* Smallest size for the 9-card layout */
        font-weight: 600;
        white-space: nowrap; /* Prevent title from wrapping */
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 100%;
    }
    
    .stat-icon {
        color: var(--kaauh-teal);
        font-size: 0.8rem; /* Small icon size */
        margin-right: 0.25rem;
        /* Note: For 9-card density, you might still want to hide this on mobile */
    }

    /* ------------------------------------------------------------- */
    /* STATS GRID LAYOUT (9 Columns) */
    /* ------------------------------------------------------------- */
    .stats {
        display: grid;
        /* Force 9 columns */
        grid-template-columns: repeat(9, 1fr); 
        gap: 0.75rem; 
        margin-bottom: 2rem;
    }

    /* Stat Card Specific Styling */
    .stat-value {
        /* This is the most important number */
        font-size: 1.5rem; /* Increased slightly for focus, was 1rem/1.25rem */
        text-align: center;
        color: var(--kaauh-teal-dark);
        font-weight: 700; 
        padding: 0.5rem 0.25rem 0.1rem; /* Very little bottom padding */
        line-height: 1.2;
    }

    .stat-caption {
        /* Smallest text for the label below the value */
        font-size: 0.7rem; /* Minimized size */
        text-align: center;
        color: #6c757d;
        padding: 0 0.25rem 0.5rem;
        line-height: 1.1;
    }

    /* ------------------------------------------------------------- */
    /* RESPONSIVE DESIGN */
    /* ------------------------------------------------------------- */
    
    /* On tablets and smaller laptops (1200px and down) */
    @media (max-width: 1200px) {
        .stats {
            /* Switch to 4 columns on medium screens */
            grid-template-columns: repeat(4, 1fr);
            gap: 1rem;
        }
        .stat-value {
            font-size: 1.75rem; /* Increase value size slightly when more space is available */
        }
        .stat-caption {
            font-size: 0.8rem;
        }
    }

    /* On phones (576px and down) */
    @media (max-width: 576px) {
        .stats {
            /* Stack to 2 columns on mobile for readability */
            grid-template-columns: repeat(2, 1fr);
            gap: 0.75rem;
        }
        .stat-value {
            font-size: 1.5rem;
        }
        .stat-caption {
            font-size: 0.75rem;
        }
    }
    
    /* Dropdown/Filter Styling */
    .job-filter-container {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    .form-select {
        border-color: var(--kaauh-border);
        border-radius: 0.5rem;
        font-size: 0.9rem;
    }
    .form-select:focus {
        border-color: var(--kaauh-teal);
        box-shadow: 0 0 0 0.2rem rgba(0, 99, 110, 0.25);
    }
    .job-filter-label {
        font-weight: 500;
        color: var(--kaauh-primary-text);
        margin: 0;
        white-space: nowrap;
    }

    /* Chart Container */
    .chart-container {
        padding: 2rem;
    }

    /* Funnel Specific Styles */
    #candidate_funnel_chart {
        max-height: 400px;
        width: 100%;
        margin: 0 auto;
    }

</style>
{% endblock %}

{% block content %}
<div class="container-fluid py-4">

    <h1 class="mb-4" style="color: var(--kaauh-teal-dark); font-weight: 700;">{% trans "Recruitment Analytics" %}</h1>

    {# -------------------------------------------------------------------------- #}
    {# JOB FILTER SECTION #}
    {# -------------------------------------------------------------------------- #}
    <div class="card mb-4">
        <div class="card-header">
            <h2>
                <i class="fas fa-search stat-icon"></i>
                {% if current_job %}
                    {% trans "Data Scope: " %}{{ current_job.title }}
                {% else %}
                    {% trans "Data Scope: All Jobs" %}
                {% endif %}
            </h2>
            {# Job Filter Dropdown #}
            <form method="get" action="" class="job-filter-container">
                <label for="job-select" class="job-filter-label d-none d-md-inline">{% trans "Filter Job:" %}</label>
                <select name="selected_job_pk" id="job-select" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="">{% trans "All Jobs (Default View)" %}</option>
                    {% for job in jobs%}
                        <option value="{{ job.pk}}" {% if current_job_id|slugify == job.pk|slugify %}selected{% endif %}>
                            {{ job.title }}
                        </option>
                    {% endfor %}
                </select>
            </form>
        </div>
    </div>
    {# -------------------------------------------------------------------------- #}
    {# STATS CARDS SECTION (12 KPIs) #}
    {# -------------------------------------------------------------------------- #}    
    {% include 'recruitment/partials/stats_cards.html' %}
    {# Note: The content of 'recruitment/partials/stats_cards.html' uses h3 which is styled correctly here #}

    {# -------------------------------------------------------------------------- #}
    {# CHARTS SECTION #}
    {# -------------------------------------------------------------------------- #}
    <div class="row g-4">
        {# AREA CHART - Daily Candidate Applications Trend (Global Chart) #}
        <div class="col-lg-12">
            <div class="card shadow-lg h-100">
                <div class="card-header">
                    <h2>
                        <i class="fas fa-chart-area stat-icon"></i>
                        {% trans "Daily Candidate Applications Trend" %}
                    </h2>
                </div>
                <div class="chart-container">
                    <canvas id="dailyApplicationsChart"></canvas>
                </div>
            </div>
        </div>
        {# BAR CHART - Application Volume (Global Chart) #}
        <div class="col-lg-6">
            <div class="card shadow-lg h-100">
                <div class="card-header">
                    <h2>
                        <i class="fas fa-chart-bar stat-icon"></i>
                        {% trans "Top 5 Application Volume" %}
                    </h2>
                </div>
                <div class="chart-container">
                    <canvas id="applicationsChart"></canvas>
                </div>
            </div>
        </div>

        {# FUNNEL CHART - Candidate Pipeline Status (Scoped Chart) #}
        <div class="col-lg-6">
            <div class="card shadow-lg h-100">
                <div class="card-header">
                    <h2>
                        <i class="fas fa-funnel-dollar stat-icon"></i>
                        {% if current_job %}
                            {% trans "Pipeline Funnel: " %}{{ current_job.title }}
                        {% else %}
                            {% trans "Total Pipeline Funnel (All Jobs)" %}
                        {% endif %}
                    </h2>
                </div>
                <div class="chart-container d-flex justify-content-center align-items-center">
                    <canvas id="candidate_funnel_chart"></canvas> 
                </div>
            </div>
        </div>

        {# GAUGE CHART - Average Time-to-Hire (Avg. Days) #}
        <div class="col-lg-12">
            <div class="card shadow-lg h-100">
                <div class="card-header">
                    <h2><i class="fas fa-tachometer-alt stat-icon"></i> {% trans "Time-to-Hire Target Check" %}</h2>
                </div>
                <div class="chart-container d-flex justify-content-center align-items-center" style="height: 300px;">
                    <div id="timeToHireGauge" class="text-center">
                        {% include "recruitment/partials/_guage_chart.html" %} 
                    </div>
                </div>
            </div>
        </div>
        
    </div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@3.4.4"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@1.3.1"></script>


<script>
    // Pass context data safely to JavaScript
    const totalCandidatesScoped = parseInt('{{ total_candidates|default:0 }}');
    const jobTitles = JSON.parse('{{ job_titles|escapejs }}').slice(0, 5);
    const jobAppCounts = JSON.parse('{{ job_app_counts|escapejs }}').slice(0, 5);
    const stages = JSON.parse('{{ candidate_stage|escapejs }}');
    const counts = JSON.parse('{{ candidates_count|safe }}');

    // --- 1. BAR CHART configuration (Top 5 Applications) ---
    const ctxBar = document.getElementById('applicationsChart').getContext('2d');
    new Chart(ctxBar, {
        type: 'bar',
        data: {
            labels: jobTitles,
            datasets: [{
                label: '{% trans "Applications" %}',
                data: jobAppCounts,
                backgroundColor: '#00636e',
                borderColor: 'var(--kaauh-teal-dark)',
                borderWidth: 1,
                barThickness: 50
            }]
        },
        options: {
            responsive: true,
            aspectRatio: 2.5,
            plugins: {
                legend: { display: false },
                title: {
                    display: true,
                    text: '{% trans "Top 5 Most Applied Jobs" %}',
                    font: { size: 16 },
                    color: 'var(--kaauh-primary-text)'
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    title: { display: true, text: '{% trans "Total Applications" %}' },
                    ticks: { color: '#2222', precision: 0 },
                    grid: { color: '#e0e0e0' }
                },
                x: {
                    ticks: { color: '#333333' },
                    grid: { display: false }
                }
            }
        }
    });


    // --- 2. CANDIDATE PIPELINE CENTERED FUNNEL CHART ---
    
    // 1. Find the maximum count (for the widest bar)
    const maxCount = Math.max(...counts);

    // 2. Calculate the transparent "spacer" data needed to center each bar
    const spacerData = counts.map(count => (maxCount - count) / 2);

    // Define the dark-to-light teal shades (5 stages, reverse order for funnel look)
    const tealShades = [
        '#00acc0', // APPLIED - Lighter Teal
        '#0093a3', // EXAM 
        '#007a88', // INTERVIEW
        '#00636e', // OFFER 
        '#004a53', // HIRED - Darkest Teal
    ];
    
    // Slice and use the first N shades based on the number of stages
    const stageColors = tealShades.slice(tealShades.length - stages.length); 

    const ctxFunnel = document.getElementById('candidate_funnel_chart').getContext('2d');

    new Chart(ctxFunnel, {
        type: 'bar', 
        data: {
            labels: stages,
            datasets: [
                // 1. TRANSPARENT SPACER DATASET (Pushes the bar to the center)
                {
                    label: 'Spacer',
                    data: spacerData,
                    backgroundColor: 'transparent',
                    hoverBackgroundColor: 'transparent',
                    barThickness: 50,
                    datalabels: { display: false }, 
                    tooltip: { enabled: false }
                },
                // 2. VISIBLE CANDIDATE COUNT DATASET
                {
                    label: '{% trans "Candidate Count" %}',
                    data: counts,
                    backgroundColor: stageColors,
                    barThickness: 50
                }
            ]
        },
        options: {
            indexAxis: 'y', 
            responsive: true,
            maintainAspectRatio: false,
            
            scales: {
                x: { 
                    beginAtZero: true,
                    stacked: true,
                    display: false,
                    max: maxCount
                },
                y: { 
                    stacked: true,
                    grid: { display: false },
                    ticks: {
                        color: 'var(--kaauh-primary-text)',
                        font: { size: 12, weight: 'bold' }
                    }
                }
            },
            plugins: {
                legend: { display: false },
                title: { display: false },
                tooltip: {
                    filter: (tooltipItem) => {
                        return tooltipItem.datasetIndex === 1; 
                    }
                }
            }
        }
    });



    // ... (after Treemap/Source Chart JS)

    // Pass context data safely to JavaScript
    const globalDates = JSON.parse('{{ global_dates|escapejs }}');
    const globalCounts = JSON.parse('{{ global_counts|escapejs }}');
    const scopedDates = JSON.parse('{{ scoped_dates|escapejs }}');
    const scopedCounts = JSON.parse('{{ scoped_counts|escapejs }}');
    const isJobScoped = '{{ is_job_scoped }}' === 'True';


    // --- 4. DAILY APPLICATIONS LINE CHART ---
    const ctxLine = document.getElementById('dailyApplicationsChart').getContext('2d');
    
    // Create datasets
    const datasets = [{
        label: '{% trans "All Jobs" %}',
        data: globalCounts,
        borderColor: '#004a53', // Dark Teal
        backgroundColor: 'rgba(0, 74, 83, 0.1)',
        fill: true,
        tension: 0.2
    }];

    // Add scoped data if a job is selected
    if (isJobScoped) {
        datasets.push({
            label: '{% trans "Current Job" %}',
            data: scopedCounts,
            borderColor: '#0093a3', // Light Teal
            backgroundColor: 'rgba(0, 147, 163, 0.1)',
            fill: true,
            tension: 0.2
        });
    }

    new Chart(ctxLine, {
        type: 'line',
        data: {
            // Use global dates as the base labels
            labels: globalDates, 
            datasets: datasets
        },
        options: {
            responsive: true,
            aspectRatio: 3.5,
            plugins: {
                legend: {
                    position: 'top',
                },
                title: {
                    display: true,
                    text: '{% trans "Daily Applications (Last 30 Days)" %}',
                    font: { size: 16 },
                    color: 'var(--kaauh-primary-text)'
                }
            },
            scales: {
                x: {
                    type: 'time',
                    time: {
                        unit: 'day',
                        tooltipFormat: 'MMM D',
                        displayFormats: {
                            day: 'MMM D'
                        }
                    },
                    title: { display: true, text: '{% trans "Date" %}' },
                    grid: { display: false }
                },
                y: {
                    beginAtZero: true,
                    title: { display: true, text: '{% trans "New Candidates" %}' },
                    ticks: { precision: 0 },
                    grid: { color: '#e0e0e0' }
                }
            }
        }
    });
    






    
</script>

{% endblock %}