const { ui, $ } = Admin;

Admin.onStatus((status) => {
  const playback = status.playbackPolicy || {};
  Admin.check($('preroll-enabled'), playback.prerollEnabled !== false);
  Admin.fill($('preroll-duration'), ((playback.prerollDurationMs || 6500) / 1000).toString());
  $('playback-state').innerHTML = $('preroll-enabled').checked
    ? ui.tag('on · ' + $('preroll-duration').value + 's', 'ok')
    : ui.tag('off', 'idle');
});

Admin.ready(() => {
  $('playback-save').addEventListener('click', () => {
    const seconds = Number($('preroll-duration').value);
    if (!Number.isFinite(seconds) || seconds < 1 || seconds > 30) {
      Admin.error('The preroll duration must be between 1 and 30 seconds.');
      return;
    }
    Admin.act(() => Admin.api('/admin/api/playback-policy', {
      method: 'POST',
      body: JSON.stringify({
        prerollEnabled: $('preroll-enabled').checked,
        prerollDurationMs: Math.round(seconds * 1000),
      }),
    }));
  });
});
