// Thin adapter between the server's notification snapshot (pushed over
// Socket.IO every 100ms) and the toast stack. The server is still the
// source of truth for info/warn/error notifications; this module just
// routes them through the toast UI and keeps the legacy
// registerNotificationAction API stable for fixtures.js + settings.js.

import {syncServerToasts, registerToastAction} from '../features/toasts.js';

export function registerNotificationAction(id, handler) {
    registerToastAction(id, handler);
}

export function renderNotifications(notifications) {
    syncServerToasts(notifications || []);
}

// Grace-period banner — subscription lapsed but app is still granting
// access. Remains a fixed top banner (not a toast) because it's a
// persistent account-level state, not a dismissible event.
export function updateGraceBanner(active, message) {
    let banner = document.getElementById('grace-banner');
    if (active) {
        if (!banner) {
            banner = document.createElement('div');
            banner.id = 'grace-banner';
            banner.style.cssText = 'position:fixed;top:0;left:0;right:0;z-index:9999;' +
                'background:#cc0000;color:#fff;text-align:center;padding:0.75rem 1rem;' +
                'font-weight:bold;font-size:0.9rem;letter-spacing:0.02em;';
            document.body.prepend(banner);
            document.body.style.paddingTop = '3rem';
        }
        banner.textContent = message || 'SUBSCRIPTION EXPIRED — GRACE PERIOD ACTIVE';
    } else if (banner) {
        banner.remove();
        document.body.style.paddingTop = '';
    }
}

// Built-in "Reset config" action shown on the config_unreadable /
// config_validation notifications.
registerNotificationAction('config_reset', async () => {
    if (!confirm('Reset ~/.conductor/config.yaml to defaults?\n\n' +
                 'A backup will be saved to ~/.conductor/backups/.')) return;
    try {
        const r = await fetch('/api/config/reset', {method: 'POST'});
        if (!r.ok) {
            const j = await r.json().catch(() => ({}));
            alert('Reset failed: ' + (j.error || r.statusText));
        }
    } catch (e) {
        alert('Reset failed: ' + e);
    }
});
