/**
 * BulkToolbar — fixed-bottom action bar for card bulk operations.
 *
 * Singleton toolbar: only one section can be in bulk mode at a time.
 * Renders dynamically based on the active section's configured actions.
 *
 * Each bulk action descriptor:
 *   { key, labelKey, icon?, style?, confirm?, handler }
 *   - icon: SVG HTML string (from icons.js) — rendered inside the button
 */

import { t } from './i18n.ts';
import { showConfirm } from './ui.ts';
import type { CardSection } from './card-sections.ts';

let _activeSection: CardSection | null = null;   // CardSection currently in bulk mode
let _toolbarEl: HTMLDivElement | null = null;        // cached DOM element

function _ensureEl() {
    if (_toolbarEl) return _toolbarEl;
    _toolbarEl = document.createElement('div');
    _toolbarEl.id = 'bulk-toolbar';
    _toolbarEl.setAttribute('role', 'toolbar');
    _toolbarEl.setAttribute('aria-label', 'Bulk actions');
    document.body.appendChild(_toolbarEl);
    return _toolbarEl;
}

/** Show the toolbar for a given section. */
export function showBulkToolbar(section) {
    if (_activeSection && _activeSection !== section) {
        _activeSection.exitSelectionMode();
    }
    _activeSection = section;
    _render();
}

/** Hide the toolbar. */
export function hideBulkToolbar() {
    _activeSection = null;
    if (_toolbarEl) _toolbarEl.classList.remove('visible');
}

/** Re-render toolbar (e.g. after selection count changes). */
export function updateBulkToolbar() {
    if (!_activeSection) return;
    _render();
}

function _render() {
    const el = _ensureEl();
    const section = _activeSection;
    if (!section) { el.classList.remove('visible'); return; }

    const count = section._selected.size;
    const actions = section.bulkActions || [];

    const actionBtns = actions.map(a => {
        const cls = a.style === 'danger' ? 'btn btn-icon btn-danger bulk-action-btn' : 'btn btn-icon btn-secondary bulk-action-btn';
        const label = t(a.labelKey);
        const inner = a.icon || label;
        return `<button class="${cls}" data-bulk-action="${a.key}" title="${label}">${inner}</button>`;
    }).join('');

    el.innerHTML = `
        <label class="bulk-select-all-wrap" title="${t('bulk.select_all')}">
            <input type="checkbox" class="bulk-select-all-cb"${count > 0 && count === section._visibleCardCount() ? ' checked' : ''}>
        </label>
        <span class="bulk-count">${t('bulk.selected_count', { count })}</span>
        <div class="bulk-actions">${actionBtns}</div>
        <button class="bulk-close" title="${t('bulk.cancel')}">&#x2715;</button>
    `;

    // Select All checkbox
    el.querySelector('.bulk-select-all-cb')!.addEventListener('change', (e) => {
        if ((e.target as HTMLInputElement).checked) section.selectAll();
        else section.deselectAll();
    });

    // Action buttons
    el.querySelectorAll('[data-bulk-action]').forEach(btn => {
        btn.addEventListener('click', () => _executeAction((btn as HTMLElement).dataset.bulkAction));
    });

    // Close button
    el.querySelector('.bulk-close')!.addEventListener('click', () => {
        section.exitSelectionMode();
    });

    el.classList.add('visible');
}

async function _executeAction(actionKey) {
    const section = _activeSection;
    if (!section) return;

    const action = section.bulkActions!.find(a => a.key === actionKey);
    if (!action) return;

    const keys = [...section._selected];
    if (!keys.length) return;

    if (action.confirm) {
        const msg = t(action.confirm, { count: keys.length });
        const ok = await showConfirm(msg);
        if (!ok) return;
    }

    // Show progress state on toolbar
    const el = _toolbarEl;
    const actionBtns = el?.querySelectorAll('.bulk-action-btn') as NodeListOf<HTMLButtonElement>;
    actionBtns?.forEach(btn => { btn.disabled = true; });
    const countEl = el?.querySelector('.bulk-count');
    const prevCount = countEl?.textContent || '';
    if (countEl) countEl.textContent = t('bulk.processing') || 'Processing…';

    try {
        await action.handler(keys);
    } catch (e) {
        console.error(`Bulk action "${actionKey}" failed:`, e);
    }

    // Restore toolbar state (in case exit doesn't happen)
    actionBtns?.forEach(btn => { btn.disabled = false; });
    if (countEl) countEl.textContent = prevCount;

    section.exitSelectionMode();
}
