document.addEventListener('DOMContentLoaded', () => {
  const request = async (action, data = {}) => {
    const body = new URLSearchParams({ action, nonce: FortisRestoreData.nonce, ...data });
    const response = await fetch(FortisRestoreData.ajax, {
      method: 'POST', credentials: 'same-origin',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body
    });
    const json = await response.json();
    if (!json.success) throw new Error(json.data?.message || 'FortisRestore request failed.');
    return json.data;
  };

  const backupButton = document.querySelector('#fortis-create');
  const backupShell = document.querySelector('#fortis-progress');
  if (backupButton && backupShell) {
    const bar = backupShell.querySelector('span');
    const label = backupShell.querySelector('p');
    const render = state => {
      backupShell.hidden = false; backupShell.dataset.job = state.id;
      bar.style.width = `${state.percent}%`; label.textContent = state.message;
      if (state.status === 'running') setTimeout(() => tick(state.id), 250);
      else if (state.status === 'complete') setTimeout(() => location.reload(), 700);
      else { backupButton.disabled = false; label.classList.add('error'); }
    };
    const tick = async id => { try { render(await request('fortis_backup_step', { job: id })); } catch (error) { label.textContent = error.message; backupButton.disabled = false; } };
    backupButton.addEventListener('click', async () => { backupButton.disabled = true; try { render(await request('fortis_backup_start')); } catch (error) { backupButton.disabled = false; label.textContent = error.message; backupShell.hidden = false; } });
    if (backupShell.dataset.job) tick(backupShell.dataset.job);
  }

  const restoreForm = document.querySelector('#fortis-restore-form');
  const restoreShell = document.querySelector('#fortis-restore-progress');
  if (restoreForm && restoreShell) {
    const startButton = document.querySelector('#fortis-restore-start');
    const cancelButton = document.querySelector('#fortis-restore-cancel');
    const bar = restoreShell.querySelector('.fortis-progress > div span, div > span');
    const label = restoreShell.querySelector(':scope > p');
    const phase = restoreShell.querySelector('[data-phase]');
    const percent = restoreShell.querySelector('[data-percent]');
    let timer;

    const render = state => {
      restoreShell.hidden = false; restoreShell.dataset.job = state.id;
      bar.style.width = `${state.percent}%`; label.textContent = state.message;
      phase.textContent = state.phase.replaceAll('_', ' ').replace(/\b\w/g, c => c.toUpperCase());
      percent.textContent = `${state.percent}%`;
      cancelButton.hidden = state.status !== 'running'; startButton.disabled = state.status === 'running';
      label.classList.toggle('error', state.status === 'failed');
      if (state.status === 'running') timer = setTimeout(() => tick(state.id), 450);
      else if (state.status === 'complete') {
        label.textContent = `Restore complete and verified${state.url ? ` · ${state.url}` : ''}`;
        if (window.FortisCelebration?.show) window.FortisCelebration.show('Restore Complete');
      }
    };
    const fail = error => { label.textContent = error.message; label.classList.add('error'); restoreShell.hidden = false; startButton.disabled = false; };
    const tick = async id => { try { render(await request('fortis_restore_step', { job: id })); } catch (error) { fail(error); } };
    restoreForm.addEventListener('submit', async event => {
      event.preventDefault();
      if (!window.confirm('Start this restore into the empty destination folder and database?')) return;
      startButton.disabled = true; const fields = Object.fromEntries(new FormData(restoreForm).entries());
      try { render(await request('fortis_restore_start', fields)); } catch (error) { fail(error); }
    });
    cancelButton.addEventListener('click', async () => {
      if (!window.confirm('Cancel this restore and remove all partially restored files and tables?')) return;
      clearTimeout(timer); cancelButton.disabled = true;
      try { render(await request('fortis_restore_cancel', { job: restoreShell.dataset.job })); } catch (error) { fail(error); }
      cancelButton.disabled = false;
    });
    if (restoreShell.dataset.job) tick(restoreShell.dataset.job);
  }
});

