(function () {
    'use strict';

    var _selectedPalette = null;
    var _activeItem      = null;
    var _originalPalette = null;
    var _dismissTimer    = null;
    var _lockedItem      = null;   // click-locked note (glow + DON/DOFF pinned)
    var _donnedItem      = null;   // currently DONned note (persistent glow)

    // ── helpers ──────────────────────────────────────────────────────────────

    function _activeModal() {
        return _activeItem && _activeItem.querySelector('.note-palette-modal');
    }

    function _paletteClass(el) {
        return Array.from(el.classList).find(function (c) { return c.startsWith('palette-'); }) || '';
    }

    function _currentBodyPalette() {
        return Array.from(document.body.classList).find(function (c) { return c.startsWith('palette-'); }) || null;
    }

    function _swapBodyPalette(paletteName) {
        var old = _currentBodyPalette();
        if (old) document.body.classList.remove(old);
        document.body.classList.add(paletteName);
    }

    function _revertBodyPalette() {
        var current = _currentBodyPalette();
        if (current) document.body.classList.remove(current);
        if (_originalPalette) document.body.classList.add(_originalPalette);
    }

    function _getCsrf() {
        var m = document.cookie.match(/csrftoken=([^;]+)/);
        return m ? m[1] : '';
    }

    function _showConfirm(modal) {
        var el = modal && modal.querySelector('.note-palette-confirm');
        if (el) el.style.display = 'flex';
    }

    function _hideConfirm(modal) {
        var el = modal && modal.querySelector('.note-palette-confirm');
        if (el) el.style.display = 'none';
    }

    // ── lock helpers ──────────────────────────────────────────────────────────

    function _clearLock() {
        if (_lockedItem) {
            _lockedItem.classList.remove('note-item--locked');
            _lockedItem = null;
        }
        document.body.classList.remove('notes-locked');
    }

    function _setGreeting(greeting, name) {
        var prefix = document.getElementById('id_greeting_prefix');
        var nameEl = document.getElementById('id_greeting_name');
        if (prefix) prefix.innerHTML = greeting;
        if (nameEl) nameEl.textContent = name;
    }

    // ── modal lifecycle ───────────────────────────────────────────────────────

    function _openModal() {
        var existing = _activeModal();
        if (!existing) {
            var tpl = _activeItem.querySelector('.note-palette-modal-tpl');
            if (!tpl) return;
            var clone = tpl.content.firstElementChild.cloneNode(true);
            _activeItem.appendChild(clone);
            _wireModal();
        }
        _activeItem.classList.add('note-item--active');
        _hideConfirm(_activeModal());
    }

    function _closeModal() {
        clearTimeout(_dismissTimer);
        _dismissTimer    = null;
        var modal        = _activeModal();
        if (modal) modal.remove();
        if (_activeItem) _activeItem.classList.remove('note-item--active');
        _activeItem      = null;
        _selectedPalette = null;
        _originalPalette = null;
    }

    function _revertPreview() {
        clearTimeout(_dismissTimer);
        _dismissTimer = null;
        _revertBodyPalette();
        var modal = _activeModal();
        if (modal) {
            modal.querySelectorAll('.note-swatch-body.previewing').forEach(function (s) {
                s.classList.remove('previewing');
            });
            _hideConfirm(modal);
        }
        _selectedPalette = null;
        _originalPalette = null;
    }

    function _wireModal() {
        var modal = _activeModal();
        if (!modal) return;

        modal.querySelectorAll('.note-swatch-body').forEach(function (body) {
            body.addEventListener('click', function (e) {
                e.stopPropagation();
                if (_selectedPalette) _revertPreview();
                _selectedPalette = _paletteClass(body.parentElement);
                _originalPalette = _currentBodyPalette();
                body.classList.add('previewing');
                _swapBodyPalette(_selectedPalette);
                _showConfirm(modal);
                _dismissTimer = setTimeout(function () { _revertPreview(); }, 10000);
            });
        });

        modal.querySelectorAll('.note-palette-confirm .btn.btn-confirm').forEach(function (btn) {
            btn.addEventListener('click', function (e) { e.stopPropagation(); _doSetPalette(); });
        });

        modal.querySelectorAll('.note-palette-confirm .btn.btn-cancel').forEach(function (btn) {
            btn.addEventListener('click', function (e) { e.stopPropagation(); _revertPreview(); });
        });

        modal.addEventListener('click', function (e) { e.stopPropagation(); });
    }

    // ── set-palette POST ──────────────────────────────────────────────────────

    function _doSetPalette() {
        var url     = _activeItem.dataset.setPaletteUrl;
        var palette = _selectedPalette;
        var item    = _activeItem;
        var swatchRow = _activeModal() && _activeModal().querySelector('.' + palette + '[data-palette-label]');
        var paletteLabel = swatchRow
            ? swatchRow.dataset.paletteLabel
            : palette.slice(8).replace(/^\w/, function (c) { return c.toUpperCase(); });
        fetch(url, {
            method: 'POST', credentials: 'same-origin',
            headers: { 'Content-Type': 'application/json', 'X-CSRFToken': _getCsrf() },
            body: JSON.stringify({ palette: palette }),
        })
        .then(function (r) { return r.json(); })
        .then(function () {
            _closeModal();
            var imageBox = item.querySelector('.note-item__image-box');
            if (imageBox) {
                var swatch = document.createElement('div');
                swatch.className = 'note-item__palette ' + palette;
                imageBox.parentNode.replaceChild(swatch, imageBox);
            }
            var list = item.querySelector('.note-recognitions__list');
            if (list && !item.querySelector('.note-recognitions__palette-line')) {
                var li = document.createElement('li');
                li.className = 'note-recognitions__palette-line';
                li.innerHTML = '<span class="note-recognitions__dim">Palette:</span> <strong>' + paletteLabel + '</strong>';
                list.appendChild(li);
            }
        });
    }

    // ── DON/DOFF ──────────────────────────────────────────────────────────────

    function _bindDonDoff(item) {
        var donBtn  = item.querySelector('.note-don-btn');
        var doffBtn = item.querySelector('.note-doff-btn');
        if (!donBtn || !doffBtn) return;

        donBtn.addEventListener('click', function (e) {
            e.stopPropagation();
            if (donBtn.classList.contains('btn-disabled')) return;
            fetch(item.dataset.donUrl, {
                method: 'POST', credentials: 'same-origin',
                headers: { 'X-CSRFToken': _getCsrf() },
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                // Auto-DOFF any previously DONned note (UI only — backend replaces active_title)
                if (_donnedItem && _donnedItem !== item) {
                    _donnedItem.classList.remove('note-item--donned');
                    var prevDon  = _donnedItem.querySelector('.note-don-btn');
                    var prevDoff = _donnedItem.querySelector('.note-doff-btn');
                    if (prevDon)  { prevDon.classList.remove('btn-disabled'); prevDon.textContent  = 'DON'; }
                    if (prevDoff) { prevDoff.classList.add('btn-disabled');    prevDoff.textContent = '×';  }
                }
                _donnedItem = item;
                item.classList.add('note-item--donned');
                // Clear lock so hover is restored for other notes
                _clearLock();
                donBtn.classList.add('btn-disabled');    donBtn.textContent  = '×';
                doffBtn.classList.remove('btn-disabled'); doffBtn.textContent = 'DOFF';
                _setGreeting(data.greeting || 'Welcome,', data.title || 'Earthman');
            });
        });

        doffBtn.addEventListener('click', function (e) {
            e.stopPropagation();
            if (doffBtn.classList.contains('btn-disabled')) return;
            fetch(item.dataset.doffUrl, {
                method: 'POST', credentials: 'same-origin',
                headers: { 'X-CSRFToken': _getCsrf() },
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                _donnedItem = null;
                item.classList.remove('note-item--donned');
                _clearLock();
                doffBtn.classList.add('btn-disabled');   doffBtn.textContent = '×';
                donBtn.classList.remove('btn-disabled'); donBtn.textContent  = 'DON';
                _setGreeting(data.greeting || 'Welcome,', data.title || 'Earthman');
            });
        });
    }

    // ── init ──────────────────────────────────────────────────────────────────

    function _init() {
        document.querySelectorAll('.note-item').forEach(function (item) {
            // Detect already-DONned note on load (DON btn is disabled = currently equipped)
            var don = item.querySelector('.note-don-btn');
            if (don && don.classList.contains('btn-disabled')) {
                item.classList.add('note-item--donned');
                _donnedItem = item;
            }

            _bindDonDoff(item);

            // Image box click → palette modal (for notes that have one)
            var box = item.querySelector('.note-item__image-box:not(.note-item__image-box--label)');
            if (box) {
                box.addEventListener('click', function (e) {
                    e.stopPropagation();
                    _activeItem = item;
                    _openModal();
                });
            }

            // Note click → toggle lock
            item.addEventListener('click', function (e) {
                e.stopPropagation();
                if (_lockedItem === item) {
                    _clearLock();
                } else {
                    _clearLock();
                    _lockedItem = item;
                    item.classList.add('note-item--locked');
                    document.body.classList.add('notes-locked');
                }
            });
        });

        // Body click → dismiss modal and clear lock
        document.body.addEventListener('click', function () {
            if (_selectedPalette) _revertPreview();
            _closeModal();
            _clearLock();
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', _init);
    } else {
        _init();
    }

    // Expose test API
    window.NotePage = {
        _init:       _init,
        _testReset:  function () {
            _selectedPalette = null;
            _activeItem      = null;
            _originalPalette = null;
            _dismissTimer    = null;
            _lockedItem      = null;
            _donnedItem      = null;
            document.body.classList.remove('notes-locked');
        },
        get _donnedItem() { return _donnedItem; },
        set _donnedItem(v) { _donnedItem = v; },
    };
}());
