// Settings page: "Discover calendars" against the CalDAV account already
// saved on this form (same idiom as frame_photos.js's Load Albums using
// the frame's already-saved Immich creds) -- so this only works after
// the CalDAV URL/username/password have been saved once.

// Hides the dedicated WebDAV username/password fields while "reuse my
// CalDAV creds" is checked -- they'd be ignored server-side anyway (see
// routers/common.py's webdav_creds_for), no reason to leave them visibly
// editable and implying they still do something.
const reuseCaldavCreds = document.getElementById('webdav_reuse_caldav_creds');
if (reuseCaldavCreds) {
  const updateWebdavFieldVisibility = () => {
    document.getElementById('webdav-creds-fields').style.display = reuseCaldavCreds.checked ? 'none' : '';
  };
  reuseCaldavCreds.addEventListener('change', updateWebdavFieldVisibility);
  updateWebdavFieldVisibility();
}

const discoverBtn = document.getElementById('caldav-discover');
if (discoverBtn) {
  discoverBtn.addEventListener('click', async () => {
    const list = document.getElementById('caldav-calendar-list');
    discoverBtn.disabled = true;
    try {
      const resp = await fetch('/api/settings/caldav-discover', { method: 'POST' });
      if (!resp.ok) throw new Error(await apiError(resp));
      const calendars = await resp.json();
      list.innerHTML = '';
      if (calendars.length === 0) {
        list.innerHTML = '<li>No calendars found in this account.</li>';
      } else {
        for (const c of calendars) {
          const li = document.createElement('li');
          li.textContent = c.display_name;
          list.appendChild(li);
        }
      }
      showStatus(true, `Found ${calendars.length} calendar${calendars.length === 1 ? '' : 's'}.`);
    } catch (e) {
      showStatus(false, e.message);
    } finally {
      discoverBtn.disabled = false;
    }
  });
}
