/**
 * Drawer primitive — slide-in panel (left/right)
 */
const { html } = window;
const { useEffect, useRef } = hooks;

export function Drawer({ open, side = 'right', width = '360px', title, children, onClose }) {
    const drawerRef = useRef(null);

    // Escape to close
    useEffect(() => {
        if (!open) return;
        const handler = (e) => {
            if (e.key === 'Escape' && onClose) onClose();
        };
        document.addEventListener('keydown', handler);
        return () => document.removeEventListener('keydown', handler);
    }, [open, onClose]);

    // Lock body scroll
    useEffect(() => {
        if (!open) return;
        document.body.style.overflow = 'hidden';
        return () => { document.body.style.overflow = ''; };
    }, [open]);

    return html`
        <div class="sw-drawer-overlay ${open ? 'sw-drawer-overlay--open' : ''}"
             onClick=${onClose}>
            <div class="sw-drawer sw-drawer--${side} ${open ? 'sw-drawer--open' : ''}"
                 ref=${drawerRef}
                 style="width:${width}"
                 onClick=${(e) => e.stopPropagation()}
                 role="dialog" aria-modal="true" aria-label=${title || 'Panel'}>
                ${title && html`
                    <div class="sw-drawer__header">
                        <h2 class="sw-drawer__title">${title}</h2>
                        ${onClose && html`
                            <button class="sw-drawer__close" onClick=${onClose} aria-label="Close">\u00d7</button>
                        `}
                    </div>
                `}
                <div class="sw-drawer__body">${children}</div>
            </div>
        </div>
    `;
}
