/** Options page — idle timeout + notification prefs + deploy folder (V2/V3). */
import {
  saveDeployHandle,
  loadDeployHandle,
  clearDeployHandle,
} from './deployFs.js';

const $ = id => document.getElementById(id);

async function load() {
  const { vaultPrefs = {} } = await chrome.storage.sync.get('vaultPrefs');
  $('idle').value = String(vaultPrefs.idleMinutes ?? 10);
  $('notify').checked = vaultPrefs.notifications !== false;
  $('lock-sleep').checked = vaultPrefs.lockOnSleep !== false;
  try {
    const h = await loadDeployHandle();
    $('folder-status').textContent = h ? `Synced folder: ${h.name}` : 'No deploy folder granted';
  } catch {
    $('folder-status').textContent = 'No deploy folder granted';
  }
}

async function save() {
  const vaultPrefs = {
    idleMinutes: Number($('idle').value),
    notifications: $('notify').checked,
    lockOnSleep: $('lock-sleep').checked,
  };
  await chrome.storage.sync.set({ vaultPrefs });
  await chrome.runtime.sendMessage({ action: 'prefs:updated' });
  $('msg').textContent = 'saved';
  setTimeout(() => { $('msg').textContent = ''; }, 1500);
}

$('idle').addEventListener('change', () => void save());
$('notify').addEventListener('change', () => void save());
$('lock-sleep').addEventListener('change', () => void save());

$('pick-folder')?.addEventListener('click', async () => {
  if (!window.showDirectoryPicker) {
    $('folder-status').textContent = 'File System Access API not available in this browser';
    return;
  }
  try {
    const handle = await window.showDirectoryPicker({ mode: 'readwrite' });
    await saveDeployHandle(handle);
    await chrome.storage.local.set({ deployFolderName: handle.name });
    $('folder-status').textContent = `Synced folder: ${handle.name} (write-only, revocable)`;
  } catch (e) {
    if (e?.name !== 'AbortError') {
      $('folder-status').textContent = e instanceof Error ? e.message : String(e);
    }
  }
});

$('clear-folder')?.addEventListener('click', async () => {
  await clearDeployHandle();
  await chrome.storage.local.remove('deployFolderName');
  $('folder-status').textContent = 'Grant revoked — no deploy folder';
});

void load();
