/**
 * Google Picker wiring for Form Forge Sheets integration.
 *
 * Flow:
 * 1. User clicks "Choose spreadsheet" (or "Create new").
 * 2. We fetch a short-lived OAuth access_token from the Worker (which
 * holds refresh_token server-side). The token has drive.file scope —
 * Picker + Drive API can only see files the user picks or the app
 * creates.
 * 3. Picker opens; on pick we stash the ID/title into the form settings
 * hidden inputs and refresh the "current" chip.
 * 4. "Create new" calls Sheets API directly with the access_token to
 * create a blank spreadsheet, then stores it as the selection.
 *
 * Keeping drive.file scope is the entire point — that's the audit-exempt
 * restricted scope Google grants without CASA review.
 */
(function () {
  if (typeof window.formforgePicker === 'undefined') return;
  var cfg = window.formforgePicker;
  var i18n = cfg.i18n;

  var pickerApiLoaded = false;
  var oauthToken = null;

  function loadPicker() {
    return new Promise(function (resolve, reject) {
      if (pickerApiLoaded) return resolve();
      if (typeof gapi === 'undefined') return reject(new Error('gapi not loaded'));
      gapi.load('picker', {
        callback: function () { pickerApiLoaded = true; resolve(); },
        onerror: function (e) { reject(e); },
      });
    });
  }

  function fetchToken() {
    if (oauthToken) return Promise.resolve(oauthToken);
    var fd = new FormData();
    fd.append('action', 'formforge_gpicker_token');
    fd.append('nonce', cfg.nonce);
    return fetch(cfg.ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' })
      .then(function (r) { return r.json(); })
      .then(function (r) {
        if (!r || !r.success) throw new Error((r && r.data && r.data.error) || i18n.not_connected);
        oauthToken = r.data.access_token;
        return oauthToken;
      });
  }

  function showPicker() {
    Promise.all([loadPicker(), fetchToken()])
      .then(function (arr) {
        var token = arr[1];
        var view = new google.picker.View(google.picker.ViewId.SPREADSHEETS);
        var picker = new google.picker.PickerBuilder()
          .addView(view)
          .setOAuthToken(token)
          .setDeveloperKey('')
          .setAppId(cfg.clientId.split('-')[0])
          .setCallback(function (data) {
            if (data.action !== google.picker.Action.PICKED) return;
            var doc = data.docs && data.docs[0];
            if (!doc) return;
 // pre-fill with 'Sheet1' so the user sees something
            // immediately, then async-resolve the real first tab name (the
            
            // or 'Sheet 1' with a space — sheets_append fails silently if
            // the range doesn't match an existing tab).
            applySelection(doc.id, doc.name, 'Sheet1');
            resolveFirstTabName(doc.id).then(function (tab) {
              if (tab && tab !== 'Sheet1') applySelection(doc.id, doc.name, tab);
            });
          })
          .build();
        picker.setVisible(true);
      })
      .catch(function (e) {
        var msg = (e && e.message) || i18n.pick_failed;
        window.alert(msg);
      });
  }

  function createNew() {
    var defaultName = i18n.default_name;
    var name = window.prompt(i18n.naming_prompt, defaultName);
    if (name === null) return;
    name = (name || defaultName).slice(0, 200);

    fetchToken()
      .then(function (token) {
        return fetch('https://sheets.googleapis.com/v4/spreadsheets', {
          method: 'POST',
          headers: {
            Authorization: 'Bearer ' + token,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ properties: { title: name } }),
        });
      })
      .then(function (r) { return r.json(); })
      .then(function (data) {
        if (!data || !data.spreadsheetId) throw new Error((data && data.error && data.error.message) || i18n.create_failed);
        var sheetName = (data.sheets && data.sheets[0] && data.sheets[0].properties && data.sheets[0].properties.title) || 'Sheet1';
        applySelection(data.spreadsheetId, data.properties.title, sheetName);
      })
      .catch(function (e) {
        window.alert((e && e.message) || i18n.create_failed);
      });
  }

  function applySelection(id, title, tab) {
    var idInput = document.getElementById('ff-gs-spreadsheet-id');
    var tabInput = document.getElementById('ff-gs-sheet-name');
    var titleInput = document.getElementById('ff-gs-spreadsheet-title');
    if (idInput) idInput.value = id;
    if (tabInput) tabInput.value = tab;
    if (titleInput) titleInput.value = title;

    var current = document.getElementById('ff-gs-current');
    var currentTitle = document.getElementById('ff-gs-current-title');
    var currentTab = document.getElementById('ff-gs-current-tab');
    var currentLink = document.getElementById('ff-gs-current-link');
    var clearBtn = document.getElementById('ff-gs-clear');
    if (current) current.style.display = id ? '' : 'none';
    if (currentTitle) currentTitle.textContent = title || '—';
    if (currentTab) currentTab.textContent = tab || 'Sheet1';
    if (currentLink && id) currentLink.href = 'https://docs.google.com/spreadsheets/d/' + id + '/edit';
    if (clearBtn) clearBtn.style.display = id ? '' : 'none';
  }

  function clearSelection() { applySelection('', '', 'Sheet1'); }

 // resolve the first tab name for a spreadsheet via Google's
  // spreadsheets.get (read-only, drive.file scope is enough since the
  // user just picked it). Falls back to 'Sheet1' if anything errors —
  // worker-side appendRow has its own fallback as a second safety net.
  function resolveFirstTabName(spreadsheetId) {
    return fetchToken()
      .then(function (token) {
        return fetch('https://sheets.googleapis.com/v4/spreadsheets/' + encodeURIComponent(spreadsheetId) + '?fields=sheets.properties.title', {
          headers: { Authorization: 'Bearer ' + token },
        });
      })
      .then(function (r) { return r.json(); })
      .then(function (data) {
        var first = data && data.sheets && data.sheets[0] && data.sheets[0].properties && data.sheets[0].properties.title;
        return first || 'Sheet1';
      })
      .catch(function () { return 'Sheet1'; });
  }

  document.addEventListener('DOMContentLoaded', function () {
    var pickBtn = document.getElementById('ff-gs-pick');
    var createBtn = document.getElementById('ff-gs-create');
    var clearBtn = document.getElementById('ff-gs-clear');
    if (pickBtn) pickBtn.addEventListener('click', showPicker);
    if (createBtn) createBtn.addEventListener('click', createNew);
    if (clearBtn) clearBtn.addEventListener('click', clearSelection);
  });
})();
