/**
 * ZERTI admin — shared team notes slide-over panel.
 */
(function () {
    'use strict';

    var cfg = window.zertiAdminNotes || {};
    var root = document.getElementById('zertiAdmin');
    if (!root) {
        return;
    }

    var panel = root.querySelector('[data-zerti-notes-panel]');
    var backdrop = root.querySelector('[data-zerti-notes-backdrop]');
    var listEl = root.querySelector('[data-zerti-notes-list]');
    var emptyEl = root.querySelector('[data-zerti-notes-empty]');
    var input = root.querySelector('[data-zerti-notes-input]');
    var editIdInput = root.querySelector('[data-zerti-notes-edit-id]');
    var saveBtn = root.querySelector('[data-zerti-notes-save]');
    var cancelBtn = root.querySelector('[data-zerti-notes-cancel]');
    var closeBtn = root.querySelector('[data-zerti-notes-close]');
    var busyEl = root.querySelector('[data-zerti-notes-busy]');
    if (!panel || !listEl || !input || !saveBtn) {
        return;
    }

    var i18n = cfg.i18n || {};
    var notes = Array.isArray(cfg.notes) ? cfg.notes.slice() : [];
    var busy = false;

    function esc(text) {
        var el = document.createElement('span');
        el.textContent = text == null ? '' : String(text);
        return el.innerHTML;
    }

    function toggles() {
        return root.querySelectorAll('[data-zerti-notes-toggle]');
    }

    function setTogglesExpanded(open) {
        toggles().forEach(function (btn) {
            btn.setAttribute('aria-expanded', open ? 'true' : 'false');
            btn.classList.toggle('is-active', !!open);
        });
    }

    function isOpen() {
        return root.classList.contains('zerti-notes-open');
    }

    function openPanel() {
        panel.hidden = false;
        if (backdrop) {
            backdrop.hidden = false;
        }
        // Allow the browser to apply display before sliding in.
        window.requestAnimationFrame(function () {
            root.classList.add('zerti-notes-open');
            panel.setAttribute('aria-hidden', 'false');
            setTogglesExpanded(true);
        });
        if (input && typeof input.focus === 'function') {
            window.setTimeout(function () {
                input.focus();
            }, 200);
        }
    }

    function closePanel() {
        root.classList.remove('zerti-notes-open');
        panel.setAttribute('aria-hidden', 'true');
        setTogglesExpanded(false);
        window.setTimeout(function () {
            if (!root.classList.contains('zerti-notes-open')) {
                panel.hidden = true;
                if (backdrop) {
                    backdrop.hidden = true;
                }
            }
        }, 230);
        resetComposer();
    }

    function resetComposer() {
        input.value = '';
        if (editIdInput) {
            editIdInput.value = '';
        }
        if (cancelBtn) {
            cancelBtn.hidden = true;
        }
        saveBtn.textContent = i18n.save || saveBtn.textContent;
    }

    function startEdit(note) {
        if (!note) {
            return;
        }
        input.value = note.text || '';
        if (editIdInput) {
            editIdInput.value = note.id || '';
        }
        if (cancelBtn) {
            cancelBtn.hidden = false;
        }
        openPanel();
        input.focus();
    }

    function formatToggleLabel(count) {
        var template = i18n.toggleLabel || 'Fast notes (%s)';
        var n = String(count);
        if (typeof window.zertiLocalizeDigits === 'function') {
            n = window.zertiLocalizeDigits(n);
        }
        return template.replace('%s', n);
    }

    function updateToggleLabels() {
        var label = formatToggleLabel(notes.length);
        toggles().forEach(function (btn) {
            var el = btn.querySelector('[data-zerti-notes-toggle-label]');
            if (el) {
                el.textContent = label;
            }
        });
    }

    function renderList() {
        listEl.innerHTML = '';
        updateToggleLabels();
        if (!notes.length) {
            if (emptyEl) {
                emptyEl.hidden = false;
            }
            return;
        }
        if (emptyEl) {
            emptyEl.hidden = true;
        }

        notes.forEach(function (note) {
            var card = document.createElement('article');
            card.className = 'zerti-notes-card';
            card.setAttribute('data-note-id', note.id || '');

            var body = document.createElement('div');
            body.className = 'zerti-notes-card__text';
            body.textContent = note.text || '';

            var meta = document.createElement('div');
            meta.className = 'zerti-notes-card__meta';
            meta.innerHTML =
                '<span class="zerti-notes-card__author">' +
                esc(note.author_name || i18n.unknownUser || '') +
                '</span>' +
                '<span class="zerti-notes-card__sep" aria-hidden="true">·</span>' +
                '<time class="zerti-notes-card__date">' +
                esc(note.date_label || '') +
                '</time>';

            var actions = document.createElement('div');
            actions.className = 'zerti-notes-card__actions';

            var edit = document.createElement('button');
            edit.type = 'button';
            edit.className = 'btn btn-link btn-sm zerti-notes-card__edit';
            edit.setAttribute('data-zerti-notes-edit', note.id || '');
            edit.setAttribute('aria-label', i18n.edit || 'Edit');
            edit.title = i18n.edit || 'Edit';
            edit.innerHTML = '<i class="fa-solid fa-pen" aria-hidden="true"></i>';

            var del = document.createElement('button');
            del.type = 'button';
            del.className = 'btn btn-link btn-sm text-danger zerti-notes-card__delete';
            del.setAttribute('data-zerti-notes-delete', note.id || '');
            del.setAttribute('aria-label', i18n.delete || 'Delete');
            del.title = i18n.delete || 'Delete';
            del.innerHTML = '<i class="fa-solid fa-trash" aria-hidden="true"></i>';

            actions.appendChild(edit);
            actions.appendChild(del);
            card.appendChild(body);
            card.appendChild(meta);
            card.appendChild(actions);
            listEl.appendChild(card);
        });
    }

    function setBusy(next) {
        busy = !!next;
        saveBtn.disabled = busy;
        if (cancelBtn) {
            cancelBtn.disabled = busy;
        }
        input.disabled = busy;
        panel.classList.toggle('is-busy', busy);
        panel.setAttribute('aria-busy', busy ? 'true' : 'false');
        if (busyEl) {
            busyEl.hidden = !busy;
            busyEl.setAttribute('aria-hidden', busy ? 'false' : 'true');
        }
        toggles().forEach(function (btn) {
            btn.disabled = busy;
        });
        if (closeBtn) {
            closeBtn.disabled = busy;
        }
    }

    function post(action, payload) {
        var body = new FormData();
        body.append('action', action);
        body.append('nonce', cfg.nonce || '');
        Object.keys(payload || {}).forEach(function (key) {
            body.append(key, payload[key] == null ? '' : String(payload[key]));
        });

        return fetch(cfg.ajaxUrl || '', {
            method: 'POST',
            credentials: 'same-origin',
            body: body,
        }).then(function (res) {
            return res.json().then(function (json) {
                if (!res.ok || !json || !json.success) {
                    var msg =
                        json && json.data && json.data.message
                            ? String(json.data.message)
                            : i18n.error || 'Request failed.';
                    throw new Error(msg);
                }
                return json.data || {};
            });
        });
    }

    function applyNotes(nextNotes) {
        notes = Array.isArray(nextNotes) ? nextNotes.slice() : [];
        renderList();
    }

    function saveNote() {
        if (busy) {
            return;
        }
        var text = String(input.value || '').trim();
        if (!text) {
            input.focus();
            return;
        }
        var id = editIdInput ? String(editIdInput.value || '').trim() : '';
        setBusy(true);
        post(cfg.saveAction || 'zerti_admin_note_save', { id: id, text: text })
            .then(function (data) {
                applyNotes(data.notes);
                resetComposer();
            })
            .catch(function (err) {
                window.alert(err && err.message ? err.message : i18n.error || 'Request failed.');
            })
            .finally(function () {
                setBusy(false);
            });
    }

    function deleteNote(id) {
        if (busy || !id) {
            return;
        }
        var message = i18n.confirmDelete || 'Delete this note?';
        var confirmApi = window.zertiConfirmAlert;
        var confirmPromise =
            confirmApi && typeof confirmApi.showDeleteConfirm === 'function'
                ? confirmApi.showDeleteConfirm(message, {
                      cancel: i18n.cancel,
                      delete: i18n.delete,
                  })
                : Promise.resolve(window.confirm(message));

        confirmPromise.then(function (ok) {
            if (!ok) {
                return;
            }
            setBusy(true);
            post(cfg.deleteAction || 'zerti_admin_note_delete', { id: id })
                .then(function (data) {
                    applyNotes(data.notes);
                    if (editIdInput && String(editIdInput.value || '') === id) {
                        resetComposer();
                    }
                })
                .catch(function (err) {
                    window.alert(err && err.message ? err.message : i18n.error || 'Request failed.');
                })
                .finally(function () {
                    setBusy(false);
                });
        });
    }

    root.addEventListener('click', function (event) {
        var target = event.target;
        if (!(target instanceof Element)) {
            return;
        }

        if (target.closest('[data-zerti-notes-toggle]')) {
            event.preventDefault();
            if (busy) {
                return;
            }
            if (isOpen()) {
                closePanel();
            } else {
                openPanel();
            }
            return;
        }

        if (target.closest('[data-zerti-notes-close]') || target.closest('[data-zerti-notes-backdrop]')) {
            event.preventDefault();
            if (busy) {
                return;
            }
            closePanel();
            return;
        }

        if (target.closest('[data-zerti-notes-save]')) {
            event.preventDefault();
            saveNote();
            return;
        }

        if (target.closest('[data-zerti-notes-cancel]')) {
            event.preventDefault();
            resetComposer();
            return;
        }

        var editBtn = target.closest('[data-zerti-notes-edit]');
        if (editBtn) {
            event.preventDefault();
            var editId = editBtn.getAttribute('data-zerti-notes-edit') || '';
            var note = notes.find(function (n) {
                return n && n.id === editId;
            });
            startEdit(note);
            return;
        }

        var deleteBtn = target.closest('[data-zerti-notes-delete]');
        if (deleteBtn) {
            event.preventDefault();
            deleteNote(deleteBtn.getAttribute('data-zerti-notes-delete') || '');
        }
    });

    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape' && isOpen() && !busy) {
            closePanel();
        }
    });

    if (closeBtn) {
        // Bound via delegated click above.
    }

    renderList();
})();
