/**
 * error-banner.js — Persistent system-error banner.
 *
 * Replaces the one-shot `notifyNotReady` toast.  Renders a sticky top bar
 * while S.systemErrors is non-empty; each error shows a reason + optional
 * [Retry init] button wired to POST /api/synapse/reinit.
 *
 * Mount: call mountErrorBanner() once from main.js after the shell renders.
 * Updates: subscribe to bus('systemErrors') and re-render on change.
 */

import { S, bus } from '../state.js';
import { post, clearSystemError } from '../api.js';

const BANNER_ID = 'nexus-error-banner';

function esc(s) {
    return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

function _render() {
    const el = document.getElementById(BANNER_ID);
    if (!el) return;

    const errors = S.systemErrors ?? [];
    if (!errors.length) {
        el.hidden = true;
        el.innerHTML = '';
        return;
    }

    el.hidden = false;
    el.innerHTML = errors.map((err) => {
        const isSynapseErr = err.code.startsWith('Synapse') ||
            err.code === 'synapse-init-failed' ||
            err.code === 'Synapse-not-ready';
        return `<div class="error-banner-row" data-code="${esc(err.code)}">
            <span class="error-banner-icon">⚠</span>
            <span class="error-banner-msg">${esc(err.message)}${err.hint ? ` — ${esc(err.hint)}` : ''}</span>
            ${isSynapseErr ? `<button class="btn btn-xs error-banner-retry" data-code="${esc(err.code)}">Retry init</button>` : ''}
            <button class="btn btn-xs error-banner-dismiss" data-code="${esc(err.code)}" aria-label="Dismiss">✕</button>
        </div>`;
    }).join('');

    // Wire retry buttons.
    el.querySelectorAll('.error-banner-retry').forEach((btn) => {
        btn.addEventListener('click', async () => {
            btn.disabled = true;
            btn.textContent = 'Retrying…';
            const result = await post('/api/synapse/reinit', {});
            if (result.ok) {
                clearSystemError(btn.dataset.code);
            } else {
                btn.disabled = false;
                btn.textContent = 'Retry init';
            }
        });
    });

    // Wire dismiss buttons.
    el.querySelectorAll('.error-banner-dismiss').forEach((btn) => {
        btn.addEventListener('click', () => clearSystemError(btn.dataset.code));
    });
}

/**
 * Mount the error banner into the shell.
 * Inserts a <div id="nexus-error-banner"> before the first child of `container`
 * (or document.body if omitted) and subscribes to S.systemErrors changes.
 */
export function mountErrorBanner(container) {
    const parent = container ?? document.body;
    let el = document.getElementById(BANNER_ID);
    if (!el) {
        el = document.createElement('div');
        el.id = BANNER_ID;
        el.className = 'error-banner';
        el.hidden = true;
        parent.insertBefore(el, parent.firstChild);
    }
    bus.on('systemErrors', _render);
    _render();
}
