/**
 * drawer.js — Persistent right drawer.
 * Replaces the modal-overlay pattern with a persistent rail.
 * openDrawer({ title, body }) / closeDrawer() / isOpen().
 */

let _open = false;
const ENTERING = 'entering';
const LEAVING  = 'leaving';

/** Open the drawer with given title and HTML body. */
export function openDrawer({ title, body }) {
    const dr  = document.getElementById('drawer');
    const ttl = document.getElementById('drawer-title');
    const bd  = document.getElementById('drawer-body');
    if (!dr || !bd) return;

    if (ttl) ttl.textContent = title || '';
    bd.innerHTML = body || _emptyPrompt();

    dr.classList.remove(LEAVING);
    dr.classList.add('open', ENTERING);
    dr.setAttribute('aria-hidden', 'false');

    // Remove entering class after animation completes (~280ms)
    setTimeout(() => dr.classList.remove(ENTERING), 300);
    _open = true;
}

/** Close the drawer. */
export function closeDrawer() {
    const dr = document.getElementById('drawer');
    if (!dr || !_open) return;

    dr.classList.add(LEAVING);
    // After leave animation, remove open + leaving
    setTimeout(() => {
        dr.classList.remove('open', LEAVING);
        dr.setAttribute('aria-hidden', 'true');
    }, 230);
    _open = false;
}

export function isOpen() { return _open; }

/** Wire close button and keyboard escape once the DOM is ready. */
export function init() {
    document.getElementById('drawer-close')?.addEventListener('click', closeDrawer);
    document.addEventListener('keydown', e => {
        if (e.key === 'Escape' && _open) closeDrawer();
    });
}

function _emptyPrompt() {
    return `<div class="drawer-empty">
        <p style="color:var(--text-dim);font-size:var(--text-sm);text-align:center;padding:24px 16px">
            Select a run, operative, or memory to inspect it here.
        </p>
    </div>`;
}
