/**
 * Documents List page: "Remove selected" and "Clear All" buttons.
 */

type AjaxResponse = { success: boolean; data?: { status?: string; error?: string } };

const LIST_URL = () => `${window.location.origin}${window.location.pathname}?page=accessible-docs-admin-documents-list`;

function setLoading(loading: boolean): void {
    document.querySelector('.js-accessible-docs-admin-loader')?.classList.toggle('active', loading);
}

function selectedIds(): string[] {
    return Array.from(document.querySelectorAll<HTMLInputElement>('.js-accessible-docs-id'))
        .filter((checkbox) => checkbox.checked)
        .map((checkbox) => checkbox.value);
}

async function send(action: string, extra: Record<string, string> = {}): Promise<void> {
    const body = new FormData();
    body.append('action', action);
    body.append('nonce', accessible_docs_admin_object.nonce);
    Object.entries(extra).forEach(([key, value]) => body.append(key, value));

    setLoading(true);
    try {
        const response = await fetch(accessible_docs_admin_object.ajax_url, { method: 'POST', body, credentials: 'same-origin' });
        const result: AjaxResponse = await response.json();
        if (!response.ok || !result.success) {
            throw new Error(result.data?.error || `Request failed (HTTP ${response.status})`);
        }
        window.location.href = LIST_URL();
    } catch (error) {
        setLoading(false);
        window.alert(error instanceof Error ? error.message : String(error));
    }
}

function init(): void {
    const removeButton = document.querySelector<HTMLButtonElement>('.js-remove-selected-button');
    const clearButton = document.querySelector<HTMLButtonElement>('.js-clear-table-button');

    if (removeButton) {
        const refresh = () => {
            removeButton.disabled = selectedIds().length === 0;
        };
        // WordPress core toggles all row checkboxes for the "select all" box without firing "change",
        // so re-check after every click inside the table.
        document.querySelector('.wp-list-table')?.addEventListener('click', () => window.setTimeout(refresh, 0));
        document.addEventListener('change', refresh);
        refresh();

        removeButton.addEventListener('click', () => {
            const ids = selectedIds();
            if (ids.length && window.confirm(removeButton.dataset.text || '')) {
                send('accessible_docs_delete_selected', { selectedIds: ids.join(',') });
            }
        });
    }

    clearButton?.addEventListener('click', () => {
        if (window.confirm(clearButton.dataset.text || '')) {
            send('accessible_docs_clear_table');
        }
    });
}

document.addEventListener('DOMContentLoaded', init);
