import { apiPatch } from './api.js';
import { showToast } from './app.js';
import { confirmAction } from './confirm-modal.js';

export function isClientArchived(c) {
    return Number(c.archived) === 1;
}

export async function confirmAndPatchClientArchive(clientCode, archived) {
    if (!(await confirmAction({
        title: archived ? 'Archive client' : 'Restore client',
        message: archived
            ? `Archive client "${clientCode}"? They will be hidden from assignments, follow-up, and the mobile app. You can restore them later from the Clients page.`
            : `Restore client "${clientCode}" to active lists?`,
        confirmLabel: archived ? 'Archive' : 'Restore',
        variant: archived ? 'danger' : 'default',
    }))) return false;

    try {
        await apiPatch('clients.php', { clientCode, archived });
        showToast(
            archived ? `Client "${clientCode}" archived` : `Client "${clientCode}" restored`,
            'success'
        );
        return true;
    } catch (e) {
        showToast(e.message, 'error');
        return false;
    }
}

/**
 * @param {object} opts
 * @param {string} opts.clientCode Escaped client code for data-code attributes
 * @param {boolean} opts.archived
 * @param {boolean} [opts.showDelete]
 * @param {string} [opts.rawCode] Unescaped code for button labels (optional)
 */
export function clientTableActionsHTML({ clientCode, archived, showDelete = false }) {
    const archiveBtn = archived
        ? `<button type="button" class="btn btn-sm restore-client-btn" data-code="${clientCode}" title="Restore to active lists">Restore</button>`
        : `<button type="button" class="btn btn-sm archive-client-btn" data-code="${clientCode}" title="Mark as finished and hide from lists">Archive</button>`;
    const deleteBtn = showDelete
        ? `<button type="button" class="btn btn-sm btn-danger delete-client-btn" data-code="${clientCode}" title="Permanently delete client and all data">Delete</button>`
        : '';

    return `<div class="table-row-actions" role="group" aria-label="Client actions">${archiveBtn}${deleteBtn}</div>`;
}
