/**
 * 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 { ICON_LIST_CHECKS, ICON_CIRCLE_OFF, ICON_X } from './icons.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 total = section._visibleCardCount();
    const actions = section.bulkActions || [];
    const allSelected = count > 0 && count === total;
    const noneSelected = count === 0;

    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;
        const disabled = noneSelected ? ' disabled aria-disabled="true"' : '';
        return `<button class="${cls}"${disabled} data-bulk-action="${a.key}" title="${label}">${inner}</button>`;
    }).join('');

    // Two distinct icon buttons replace the previous tri-state checkbox so
    // the affordance is unambiguous: pick everything, or clear the picks.
    const selectAllDisabled = allSelected ? ' disabled aria-disabled="true"' : '';
    const deselectAllDisabled = noneSelected ? ' disabled aria-disabled="true"' : '';

    el.innerHTML = `
        <div class="bulk-pick">
            <button class="bulk-pick-btn" data-bulk-pick="all"${selectAllDisabled} title="${t('bulk.select_all')}" aria-label="${t('bulk.select_all')}">${ICON_LIST_CHECKS}</button>
            <button class="bulk-pick-btn" data-bulk-pick="none"${deselectAllDisabled} title="${t('bulk.deselect_all')}" aria-label="${t('bulk.deselect_all')}">${ICON_CIRCLE_OFF}</button>
        </div>
        <span class="bulk-count" aria-live="polite">${t('bulk.selected_count', { count })}<small class="bulk-count-total"> / ${total}</small></span>
        <div class="bulk-actions">${actionBtns}</div>
        <button class="bulk-close" title="${t('bulk.cancel')}" aria-label="${t('bulk.cancel')}">${ICON_X}</button>
    `;

    // Pick buttons
    el.querySelector('[data-bulk-pick="all"]')!.addEventListener('click', () => {
        section.selectAll();
    });
    el.querySelector('[data-bulk-pick="none"]')!.addEventListener('click', () => {
        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();
}
