{% extends 'base.html' %}
{% load static %}

{% block title %}Enter Marks — {{ cls.name }} Term {{ term.term }} — Rapha-Bethel BNPS{% endblock %}

{% block extra_css %}
<style>
/* ── Layout ── */
.marks-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; }

/* ── Sticky header + first col ── */
.marks-table { border-collapse: collapse; min-width: 100%; font-size: .78rem; }
.marks-table thead th {
    position: sticky; top: 0; z-index: 10;
    background: #1e3a5f; color: #fff;
    padding: 7px 6px; white-space: nowrap;
    border: 1px solid #2d4f7a; font-weight: 600;
}
.marks-table thead th.domain-header {
    background: #162d4a; font-size: .7rem;
    letter-spacing: .3px; text-transform: uppercase;
}
.marks-table td {
    border: 1px solid #e5e7eb; padding: 3px 4px;
    vertical-align: middle;
}
.marks-table td.student-cell {
    position: sticky; left: 0; z-index: 5;
    background: #f8fafc; min-width: 140px; max-width: 160px;
    font-weight: 600; font-size: .76rem;
    border-right: 2px solid #cbd5e1;
    white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.marks-table tr:hover td { background: #f0f7ff; }
.marks-table tr:hover td.student-cell { background: #e8f0fe; }

/* ── Score inputs ── */
.score-input {
    width: 44px; border: 1px solid #d1d5db; border-radius: 5px;
    padding: 3px 4px; text-align: center; font-size: .8rem;
    background: #fff; transition: border-color .15s, box-shadow .15s;
    -moz-appearance: textfield;
}
.score-input::-webkit-outer-spin-button,
.score-input::-webkit-inner-spin-button { -webkit-appearance: none; }
.score-input:focus { outline: none; border-color: #3b82f6; box-shadow: 0 0 0 2px rgba(59,130,246,.2); }
.score-input.changed { border-color: #f59e0b; background: #fffbeb; }
.score-input.saved   { border-color: #10b981; background: #f0fdf4; }
.score-input.error   { border-color: #ef4444; background: #fef2f2; }
.score-input.over    { border-color: #ef4444; color: #ef4444; }

/* ── Domain sub-header rows ── */
tr.domain-row td {
    background: #f1f5f9; font-weight: 700; font-size: .7rem;
    text-transform: uppercase; letter-spacing: .4px; color: #475569;
    border-top: 2px solid #cbd5e1; padding: 5px 8px;
}

/* ── Save bar ── */
.save-bar {
    position: sticky; bottom: 0; z-index: 20;
    background: #1e3a5f; color: #fff;
    padding: 10px 16px; border-radius: 10px 10px 0 0;
    display: flex; align-items: center; justify-content: space-between;
    flex-wrap: wrap; gap: 8px;
    box-shadow: 0 -4px 20px rgba(0,0,0,.15);
}
.save-bar .unsaved-count {
    font-size: .82rem; opacity: .85;
}
.save-bar .btn-save-all {
    background: #10b981; border: none; color: #fff;
    padding: 7px 20px; border-radius: 6px; font-weight: 700;
    font-size: .84rem; cursor: pointer; transition: background .15s;
}
.save-bar .btn-save-all:hover { background: #059669; }
.save-bar .btn-save-all:disabled { background: #6b7280; cursor: default; }

/* ── Status toast ── */
#saveToast {
    position: fixed; bottom: 70px; right: 20px; z-index: 9999;
    background: #1e293b; color: #fff; border-radius: 8px;
    padding: 10px 16px; font-size: .82rem; display: none;
    box-shadow: 0 4px 20px rgba(0,0,0,.25);
}
#saveToast.success { background: #065f46; }
#saveToast.error   { background: #7f1d1d; }

/* ── Toolbar ── */
.rc-toolbar {
    background: #fff; border: 1px solid #e5e7eb; border-radius: 10px;
    padding: 12px 16px; margin-bottom: 14px;
    display: flex; align-items: center; flex-wrap: wrap; gap: 10px;
}

/* ── Student ID badge ── */
.sid { font-size: .65rem; color: #94a3b8; font-family: monospace; }

/* ── Month column headers ── */
th.month-col { font-size: .68rem; min-width: 48px; }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid px-2 px-md-3">

    <!-- Breadcrumb -->
    <nav aria-label="breadcrumb" style="font-size:.8rem" class="mb-2">
        <ol class="breadcrumb mb-0">
            <li class="breadcrumb-item"><a href="{% url 'rc-dashboard' %}">Report Cards</a></li>
            <li class="breadcrumb-item active">{{ cls.name }} — Term {{ term.term }}</li>
        </ol>
    </nav>

    <!-- Header -->
    <div class="d-flex justify-content-between align-items-start mb-2 flex-wrap gap-2">
        <div>
            <h1 class="h4 mb-0">
                <i class="fas fa-pencil-alt me-2 text-primary"></i>
                Enter Marks — {{ cls.name }}
            </h1>
            <p class="text-muted mb-0" style="font-size:.82rem">
                Term {{ term.term }} &nbsp;·&nbsp; {{ term.academic_year }}
                &nbsp;·&nbsp; {{ student_count }} student{{ student_count|pluralize }}
                &nbsp;·&nbsp; <span class="badge bg-primary" style="font-size:.68rem">{{ rtype|upper }}</span>
            </p>
        </div>
        <!-- Term switcher -->
        <div class="d-flex gap-2 flex-wrap">
            {% for t in all_terms %}
            <a href="{% url 'rc-marks' cls.pk t.pk %}"
               class="btn btn-sm {% if t.pk == term.pk %}btn-primary{% else %}btn-outline-secondary{% endif %}">
                T{{ t.term }} {{ t.academic_year }}
                {% if t.is_current %}<i class="fas fa-circle ms-1" style="font-size:.4rem;vertical-align:middle"></i>{% endif %}
            </a>
            {% endfor %}
        </div>
    </div>

    <!-- Toolbar -->
    <div class="rc-toolbar">
        <!-- Initialise if not done -->
        {% if not rc_initialised %}
        <form method="post" action="{% url 'rc-init-class' cls.pk term.pk %}" class="d-inline">
            {% csrf_token %}
            <button type="submit" class="btn btn-warning btn-sm">
                <i class="fas fa-magic me-1"></i>Initialise Report Cards ({{ student_count }} students)
            </button>
        </form>
        <span class="text-muted" style="font-size:.78rem">
            <i class="fas fa-exclamation-circle me-1 text-warning"></i>
            Report cards not yet created for this class/term — initialise first.
        </span>
        {% else %}
        <span class="text-success" style="font-size:.8rem">
            <i class="fas fa-check-circle me-1"></i>{{ rc_count }} report card{{ rc_count|pluralize }} initialised
        </span>

        <!-- Compute all -->
        <form method="post" action="{% url 'rc-compute-class' cls.pk term.pk %}" class="d-inline" id="computeForm">
            {% csrf_token %}
            <button type="submit" class="btn btn-info btn-sm text-white" id="computeBtn">
                <i class="fas fa-calculator me-1"></i>Compute Averages &amp; Positions
            </button>
        </form>

        <!-- Bulk PDF -->
        <a href="{% url 'rc-bulk' cls.pk term.pk %}" class="btn btn-outline-dark btn-sm" target="_blank">
            <i class="fas fa-file-pdf me-1 text-danger"></i>Bulk PDF (all students)
        </a>
        {% endif %}

        <!-- Save all button (also in sticky bar) -->
        <button class="btn btn-success btn-sm ms-auto" id="saveAllBtn" disabled>
            <i class="fas fa-save me-1"></i>Save All Changes
            <span id="unsavedBadge" class="badge bg-warning text-dark ms-1" style="display:none"></span>
        </button>
    </div>

    {% if student_rows %}
    <!-- Marks grid -->
    <div class="marks-wrap">
        <table class="marks-table" id="marksTable">
            <thead>
                <!-- Domain header row -->
                <tr>
                    <th rowspan="2" style="min-width:140px;left:0;z-index:12;background:#162d4a">
                        Student
                    </th>
                    {% for group in subject_groups %}
                    <th class="domain-header text-center"
                        colspan="{{ group.subjects|length|add:group.subjects|length|add:group.subjects|length }}">
                        {# colspan = subjects × 3 months — computed in JS #}
                        {{ group.domain }}
                    </th>
                    {% endfor %}
                </tr>
                <!-- Subject + month sub-headers -->
                <tr>
                    {% for group in subject_groups %}
                    {% for subj in group.subjects %}
                    {% for mn in month_nums %}
                    <th class="month-col text-center"
                        data-subject="{{ subj.id }}" data-month="{{ mn }}"
                        title="{{ subj.sub_activity }}">
                        {% if forloop.first %}
                        <div style="font-size:.62rem;color:#94a3b8;font-weight:400;white-space:normal;max-width:50px;line-height:1.2">
                            {{ subj.sub_activity|truncatechars:12 }}
                        </div>
                        {% endif %}
                        <div>M{{ mn }}</div>
                    </th>
                    {% endfor %}
                    {% endfor %}
                    {% endfor %}
                </tr>
            </thead>
            <tbody>
                {% for row in student_rows %}
                <tr data-student="{{ row.student.pk }}">
                    <td class="student-cell" title="{{ row.student.get_full_name }}">
                        <div>{{ row.student.last_name|upper }}, {{ row.student.first_name }}</div>
                        <div class="sid">{{ row.student.student_id }}</div>
                    </td>
                    {% for cell in row.cells %}
                    {% for score_item in cell.scores %}
                    <td class="text-center" style="padding:2px 3px">
                        <input
                            type="number"
                            class="score-input"
                            min="0" max="20" step="0.5"
                            data-student="{{ row.student.pk }}"
                            data-subject="{{ cell.subject.pk }}"
                            data-month="{{ score_item.month }}"
                            value="{{ score_item.score }}"
                            placeholder="—"
                            autocomplete="off"
                        >
                    </td>
                    {% endfor %}
                    {% endfor %}
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>

    <!-- Sticky save bar -->
    <div class="save-bar" id="saveBar" style="display:none">
        <span class="unsaved-count">
            <i class="fas fa-edit me-1"></i>
            <span id="barUnsavedCount">0</span> unsaved change(s)
        </span>
        <div class="d-flex gap-2 align-items-center">
            <span id="barStatus" style="font-size:.78rem;opacity:.8"></span>
            <button class="btn-save-all" id="barSaveBtn">
                <i class="fas fa-save me-1"></i>Save All
            </button>
        </div>
    </div>

    {% else %}
    <div class="text-center py-5 text-muted">
        <i class="fas fa-users fa-3x mb-3 d-block"></i>
        <h5>No active students in this class</h5>
        <p>Assign students to <strong>{{ cls.name }}</strong> first.</p>
    </div>
    {% endif %}

</div>

<!-- Toast notification -->
<div id="saveToast"></div>
{% endblock %}

{% block extra_js %}
<script>
(function () {
    const SAVE_URL  = "{% url 'rc-save-marks' cls.pk term.pk %}";
    const CSRF      = "{{ csrf_token }}";

    // Track pending changes per student: {studentId: [{subject_id, month, score}]}
    const pending = {};
    let saving = false;

    // ── Listen for input changes ──────────────────────────────
    document.querySelectorAll('.score-input').forEach(input => {
        input.addEventListener('input', function () {
            const val = this.value.trim();
            const sid = this.dataset.student;
            const subj = this.dataset.subject;
            const month = this.dataset.month;

            // Validate
            if (val !== '' && (parseFloat(val) > 20 || parseFloat(val) < 0)) {
                this.classList.add('over');
            } else {
                this.classList.remove('over');
            }

            this.classList.add('changed');
            this.classList.remove('saved', 'error');

            // Register change
            if (!pending[sid]) pending[sid] = {};
            const key = `${subj}_${month}`;
            pending[sid][key] = { subject_id: parseInt(subj), month: parseInt(month), score: val };

            updateUI();
        });
    });

    // ── Count pending ─────────────────────────────────────────
    function countPending() {
        return Object.values(pending).reduce((t, m) => t + Object.keys(m).length, 0);
    }

    function updateUI() {
        const n = countPending();
        const saveAllBtn = document.getElementById('saveAllBtn');
        const barSaveBtn = document.getElementById('barSaveBtn');
        const saveBar    = document.getElementById('saveBar');
        const badge      = document.getElementById('unsavedBadge');
        const barCount   = document.getElementById('barUnsavedCount');

        saveAllBtn.disabled = (n === 0 || saving);
        barSaveBtn.disabled = (n === 0 || saving);

        if (n > 0) {
            saveBar.style.display = 'flex';
            badge.style.display = 'inline';
            badge.textContent = n;
            barCount.textContent = n;
        } else {
            saveBar.style.display = 'none';
            badge.style.display = 'none';
        }
    }

    // ── Save all pending changes ──────────────────────────────
    async function saveAll() {
        if (saving || countPending() === 0) return;
        saving = true;

        document.getElementById('saveAllBtn').disabled = true;
        document.getElementById('barSaveBtn').disabled = true;
        document.getElementById('barStatus').textContent = 'Saving…';

        const studentIds = Object.keys(pending);
        let totalSaved = 0;
        let totalErrors = [];

        for (const sid of studentIds) {
            const marks = Object.values(pending[sid]);
            try {
                const resp = await fetch(SAVE_URL, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRFToken': CSRF,
                    },
                    body: JSON.stringify({ student_id: parseInt(sid), marks }),
                });
                const data = await resp.json();
                totalSaved += data.saved || 0;
                if (data.errors && data.errors.length) {
                    totalErrors.push(...data.errors);
                }
                // Mark inputs as saved
                Object.keys(pending[sid]).forEach(key => {
                    const [subj, month] = key.split('_');
                    const input = document.querySelector(
                        `.score-input[data-student="${sid}"][data-subject="${subj}"][data-month="${month}"]`
                    );
                    if (input) {
                        input.classList.remove('changed');
                        input.classList.add('saved');
                        setTimeout(() => input.classList.remove('saved'), 2000);
                    }
                });
                delete pending[sid];
            } catch (e) {
                totalErrors.push(`Student ${sid}: ${e.message}`);
            }
        }

        saving = false;
        updateUI();

        if (totalErrors.length) {
            showToast(`Saved ${totalSaved}, but errors: ${totalErrors.join('; ')}`, 'error');
        } else {
            showToast(`✅ Saved ${totalSaved} mark(s) successfully`, 'success');
        }
        document.getElementById('barStatus').textContent = '';
    }

    // ── Wire save buttons ─────────────────────────────────────
    document.getElementById('saveAllBtn').addEventListener('click', saveAll);
    document.getElementById('barSaveBtn').addEventListener('click', saveAll);

    // Auto-save when leaving page
    window.addEventListener('beforeunload', function (e) {
        if (countPending() > 0) {
            e.preventDefault();
            e.returnValue = 'You have unsaved marks. Are you sure you want to leave?';
        }
    });

    // Keyboard: Enter moves to next input in same column
    document.querySelectorAll('.score-input').forEach((input, idx, all) => {
        input.addEventListener('keydown', function (e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                // Find next input in same subject/month column (next student)
                const subj  = this.dataset.subject;
                const month = this.dataset.month;
                const allSame = [...document.querySelectorAll(
                    `.score-input[data-subject="${subj}"][data-month="${month}"]`
                )];
                const i = allSame.indexOf(this);
                if (i < allSame.length - 1) allSame[i + 1].focus();
            }
            if (e.key === 'Tab') {
                // Default tab behaviour — moves across months then subjects
            }
        });
    });

    // ── Toast ─────────────────────────────────────────────────
    function showToast(msg, type) {
        const t = document.getElementById('saveToast');
        t.textContent = msg;
        t.className = type || '';
        t.style.display = 'block';
        setTimeout(() => { t.style.display = 'none'; }, 3500);
    }

    // ── Fix domain header colspans ────────────────────────────
    // The Django template can't easily compute subject×3 colspans, so fix in JS
    document.querySelectorAll('th.domain-header').forEach(th => {
        // Count how many month-col th's follow until the next domain-header
        // Simpler: count children in the next header row under this domain
        // We set data-domain on each month-col, then count
    });
    // Recompute colspans from actual rendered month columns
    (function fixColspans() {
        const domainHeaders = document.querySelectorAll('th.domain-header');
        const monthCols     = document.querySelectorAll('th.month-col');
        if (!domainHeaders.length) return;

        // Group month cols by their data-subject, then map to domain
        // Simpler: just count cells between domain header boundaries
        // We'll use the subject_groups data rendered in a hidden element
        const groups = document.querySelectorAll('[data-domain-group]');
        if (groups.length === domainHeaders.length) {
            groups.forEach((g, i) => {
                domainHeaders[i].colSpan = parseInt(g.dataset.colspan);
            });
        }
    })();

    updateUI();
})();
</script>

<!-- Hidden domain colspan data for JS -->
{% for group in subject_groups %}
<div data-domain-group="{{ forloop.counter }}"
     data-colspan="{{ group.subjects|length|add:group.subjects|length|add:group.subjects|length }}"
     style="display:none"></div>
{% endfor %}
{% endblock %}
