/*
Milestone 2A frontend patch
- Adds family-aware caregiver login
- Loads family context and clients from server
- Leaves most of the existing UI intact for low-risk testing
*/

const CAREGIVER_LOGIN_API = '/api/caregiver_login.php';
const FAMILY_CONTEXT_API = '/api/family_context.php';
const CLIENTS_API = '/api/clients.php';
const LOGOUT_API = '/api/logout.php';

async function apiJson(url, options = {}) {
  const res = await fetch(url, {
    credentials: 'same-origin',
    headers: {
      'Accept': 'application/json',
      ...(options.body && !(options.body instanceof FormData) ? { 'Content-Type': 'application/json' } : {}),
      ...(options.headers || {})
    },
    ...options
  });

  const data = await res.json().catch(() => ({}));
  if (!res.ok || data.success === false) {
    throw new Error(data.message || `Request failed: ${res.status}`);
  }
  return data;
}

async function caregiverServerLogin() {
  const familySlug = document.getElementById('loginFamilySlug')?.value.trim() || '';
  const username = document.getElementById('loginCaregiverSelect')?.value.trim() || '';
  const pin = document.getElementById('loginPin')?.value || '';

  if (!familySlug || !username || !pin) {
    alert('Enter family slug, caregiver username, and PIN.');
    return;
  }

  const payload = { family_slug: familySlug, username, pin };
  const login = await apiJson(CAREGIVER_LOGIN_API, {
    method: 'POST',
    body: JSON.stringify(payload)
  });

  const context = await apiJson(FAMILY_CONTEXT_API);
  const clients = await apiJson(CLIENTS_API);

  appState.activeCaregiverSession = {
    family: context.family,
    caregiver: context.caregiver,
    settings: context.settings,
    serverBacked: true,
    serverSessionToken: login.session_token
  };

  appState.clients = ['Select Client', ...clients.clients.map(c => c.client_name)];
  renderClientCaregiverLists();

  if (els.loggedInInfo) {
    els.loggedInInfo.textContent = `Logged in as ${context.caregiver?.name || 'caregiver'} | Family: ${context.family?.name || ''}`;
  }

  if (els.caregiverSelect && context.caregiver?.name) {
    if (![...els.caregiverSelect.options].some(o => o.value === context.caregiver.name)) {
      const opt = document.createElement('option');
      opt.value = context.caregiver.name;
      opt.textContent = context.caregiver.name;
      els.caregiverSelect.appendChild(opt);
    }
    els.caregiverSelect.value = context.caregiver.name;
  }

  els.caregiverLoginScreen.classList.add('hidden');
  els.appShell.classList.remove('hidden');
  setStatus('Loaded family data from server');
}

async function serverLogoutThenResetUi() {
  try {
    await apiJson(LOGOUT_API, { method: 'POST' });
  } catch (err) {
    console.warn('Server logout failed', err);
  }

  appState.activeCaregiverSession = null;
  els.appShell.classList.add('hidden');
  els.caregiverLoginScreen.classList.remove('hidden');
}

/*
Add this field to your caregiver login screen above caregiver select:

<div class="field">
  <label for="loginFamilySlug">Family Slug</label>
  <input id="loginFamilySlug" type="text" placeholder="wear-family" autocomplete="off" />
</div>

Then replace the existing login button handler to call caregiverServerLogin().
Replace the logout button handler to call serverLogoutThenResetUi().
*/
