/* Airtable waitlist persistence — writes emails to your Emails table.
   Uses the REST API directly from the browser (PAT is visible client-side).
   For a production app, proxy this through a serverless function. */

const AIRTABLE_CONFIG = {
  BASE_ID: 'appVgpCLHmiIOV3Wt',
  TABLE_NAME: 'Emails',
  /* Personal Access Token — scoped to data.records:write on this base.
     In production, move this server-side. */
  PAT: 'patMNXbu37Uh7SYcA.4ea5b23d1a6565e3915d6585576018f8a8168b155ce427bfdee5dad2e134de45',
};

const AIRTABLE_URL = `https://api.airtable.com/v0/${AIRTABLE_CONFIG.BASE_ID}/${AIRTABLE_CONFIG.TABLE_NAME}`;

/**
 * Save an email address and referral source to Airtable.
 * Returns the created record on success, null on failure (non-blocking).
 */
async function ppSaveToAirtable(email, source) {
  try {
    const body = {
      records: [{
        fields: {
          Email: email,
          CreatedAt: new Date().toISOString(),
          Source: source || 'direct',
        },
      }],
    };

    const res = await fetch(AIRTABLE_URL, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${AIRTABLE_CONFIG.PAT}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(body),
    });

    if (!res.ok) {
      const errBody = await res.text().catch(() => '');
      console.warn('[Airtable] POST failed:', res.status, errBody);
      return null;
    }

    const data = await res.json();
    console.log('[Airtable] Record created:', data.records?.[0]?.id);
    return data.records?.[0] ?? null;
  } catch (err) {
    console.warn('[Airtable] Network error:', err);
    return null;
  }
}

Object.assign(window, { ppSaveToAirtable });
