import { dom, qs$, qsa$ } from './dom.js';
import { deepT } from './deepblocker-i18n.js';
import { applyProtectionPreset, savePresetChoice } from './deepblocker-presets.js';

/******************************************************************************/

let selectedPreset = 'strong';

const setStatus = text => {
    const node = qs$('#welcomeStatus');
    if ( node !== null ) {
        node.textContent = text;
    }
};

const openDashboard = (pane = 'settings.html') => {
    self.location.href = `dashboard.html#${pane}`;
};

const setBusy = state => {
    for ( const button of qsa$('button') ) {
        button.disabled = state;
    }
};

dom.on('.deep-preset', 'click', ev => {
    const button = ev.currentTarget;
    selectedPreset = button.dataset.preset || 'strong';
    dom.cl.remove('.deep-preset.selected', 'selected');
    dom.cl.add(button, 'selected');
});

dom.on('#applyWelcomePreset', 'click', async ( ) => {
    setBusy(true);
    setStatus(await deepT('applyingPreset'));
    try {
        await applyProtectionPreset(selectedPreset, { reload: true });
        setStatus(await deepT('protectionReady'));
        openDashboard('settings.html');
    } catch (ex) {
        setStatus(await deepT('presetFailed'));
        console.warn('DeepBlocker welcome preset failed', ex);
        setBusy(false);
    }
});

dom.on('#skipWelcome', 'click', async ( ) => {
    await savePresetChoice(selectedPreset);
    openDashboard('settings.html');
});

/******************************************************************************/
