{% extends "core/base.html" %}

{% block title_text %}{{ room.name }} — Billscroll{% endblock %}
{% block header_text %}<span>Bill</span><span>scroll</span>{% endblock header_text %}

{% block content %}
{% csrf_token %}
<div class="billscroll-page">
    {% include "apps/applets/_partials/_gear.html" with menu_id="id_billscroll_menu" %}
    <div id="id_billscroll_menu" style="display:none;">
        <form id="id_scroll_filter_form">
            <label><input type="checkbox" name="labels" value="frame" checked> Frame</label>
            <label><input type="checkbox" name="labels" value="redact" checked> Redact</label>
            <div class="menu-btns">
                <button type="submit" class="btn btn-confirm">OK</button>
                <button type="button" class="btn btn-cancel applet-menu-cancel">NVM</button>
            </div>
        </form>
    </div>
    {% include "apps/billboard/_partials/_applet-scroll.html" %}
</div>
<script>
(function () {
    var STORAGE_KEY = 'billscroll-labels-{{ room.id }}';
    var ALL_LABELS  = ['frame', 'redact'];

    function applyFilter(checked) {
        document.querySelectorAll(
            '#id_drama_scroll .drama-event[data-label]'
        ).forEach(function (el) {
            el.style.display = checked.indexOf(el.dataset.label) !== -1 ? '' : 'none';
        });
    }

    function saveFilter(checked) {
        try { localStorage.setItem(STORAGE_KEY, JSON.stringify(checked)); } catch (_) {}
    }

    function loadFilter() {
        try {
            var raw = localStorage.getItem(STORAGE_KEY);
            return raw ? JSON.parse(raw) : null;
        } catch (_) { return null; }
    }

    function syncCheckboxes(checked) {
        var form = document.getElementById('id_scroll_filter_form');
        if (!form) return;
        form.querySelectorAll('input[name="labels"]').forEach(function (cb) {
            cb.checked = checked.indexOf(cb.value) !== -1;
        });
    }

    // Restore saved filter on page load
    var saved = loadFilter();
    if (saved) {
        applyFilter(saved);
        syncCheckboxes(saved);
    }

    // Apply + save on OK
    var form = document.getElementById('id_scroll_filter_form');
    if (!form) return;
    form.addEventListener('submit', function (e) {
        e.preventDefault();
        var checked = Array.from(
            form.querySelectorAll('input[name="labels"]:checked')
        ).map(function (cb) { return cb.value; });
        applyFilter(checked);
        saveFilter(checked);
        // Close the menu (mirror applets.js close logic)
        var menu = document.getElementById('id_billscroll_menu');
        if (menu) menu.style.display = 'none';
        var gear = document.querySelector(
            '.gear-btn[data-menu-target="id_billscroll_menu"]'
        );
        if (gear) gear.classList.remove('active');
    });
}());
</script>
{% endblock %}
