import type { ApiResponse } from '../types/api/ApiResponse';

/**
 * Dashboard switch cards (`.card--toggle`): mode maintenance, blocage de la
 * préhome, and anything added later.
 *
 * Each switch declares its own endpoint and wording on the input, so a new card
 * is a Twig-only change — no branch to add here.
 */
const toggles = document.querySelectorAll<HTMLInputElement>('input[type="checkbox"][data-toggle-endpoint]');

toggles.forEach((checkbox: HTMLInputElement) => {
    const endpoint = checkbox.dataset.toggleEndpoint;
    const label = checkbox.dataset.toggleLabel ?? 'ce réglage';

    if (!endpoint) {
        return;
    }

    checkbox.addEventListener('change', () => {
        checkbox.disabled = true;

        const revert = (): void => {
            alert(`Erreur lors de la modification du ${label}`);
            checkbox.checked = !checkbox.checked;
            checkbox.disabled = false;
        };

        fetch(endpoint, { method: 'POST' })
            .then(response => response.json())
            .then((data: ApiResponse<{ isEnabled: boolean }>) => {
                if (!data.success) {
                    revert();

                    return;
                }
                // Trust the server's state rather than the optimistic one.
                checkbox.checked = data.data?.isEnabled ?? checkbox.checked;
                checkbox.disabled = false;
            })
            .catch(revert);
    });
});
