// forms-sync.jsx
// Fire-and-forget Google Forms POST so completion + packet records pool
// across student devices (in addition to the local localStorage cache).
// All fetches use { mode: 'no-cors' } — Google Forms doesn't return CORS
// headers, so the response is opaque. Records still land in the form's
// response Sheet either way.

(function () {
  const COMPLETIONS_ACTION = 'https://docs.google.com/forms/d/e/1FAIpQLSdF30xyMgGMtxGPSbRMzjyLK9i1ysHwW6j3VS2SKTSePnlViw/formResponse';
  const COMPLETIONS_ENTRIES = {
    'Name':            'entry.245664751',
    'Email':           'entry.586620296',
    'Section':         'entry.206641898',
    'Squad Name':      'entry.428919494',
    'Role':            'entry.724797528',
    'Difficulty':      'entry.1978565859',
    'Total XP':        'entry.1060137125',
    'Datastream Score':'entry.1366417779',
    'Heist Score':     'entry.251886785',
    'Policy Score':    'entry.1955914096',
    'Triage Score':    'entry.1668137284',
    'HexSweep Score':  'entry.1267249591',
    'Grade':           'entry.1731039849',
    'Passed':          'entry.740838716',
    'Duration (sec)':  'entry.740014177',
    'Completed At':    'entry.710290780',
    'Signed In At':    'entry.1251010208',
  };

  const PACKETS_ACTION = 'https://docs.google.com/forms/d/e/1FAIpQLSfsDo-K8ynJdsxFm9kWFOYoSax58GFoixsDd_e4xxfiV8J90w/formResponse';
  const PACKETS_ENTRIES = {
    'Type':          'entry.1941832025',
    'Tag':           'entry.148205830',
    'Message':       'entry.1792205731',
    'Source Phase':  'entry.698488041',
    'Anonymous':     'entry.1071630995',
    'Student Name':  'entry.781058091',
    'Student Email': 'entry.40493570',
    'Section':       'entry.627892574',
    'Squad Name':    'entry.1290042234',
    'Awarded XP':    'entry.506472675',
    'Submitted At':  'entry.385384786',
  };

  function postFields(action, entries, fields) {
    try {
      const body = new URLSearchParams();
      for (const [name, value] of Object.entries(fields)) {
        const entryId = entries[name];
        if (entryId && value !== undefined && value !== null) {
          body.append(entryId, String(value));
        }
      }
      // no-cors → opaque response, but the form still records the submission.
      fetch(action, { method: 'POST', mode: 'no-cors', body }).catch(() => {});
    } catch (e) { /* don't let Form errors break the game */ }
  }

  function postCompletion(rec) {
    if (!rec) return;
    postFields(COMPLETIONS_ACTION, COMPLETIONS_ENTRIES, {
      'Name':             rec.name,
      'Email':            rec.email,
      'Section':          rec.section,
      'Squad Name':       rec.squadName || '',
      'Role':             rec.role || '',
      'Difficulty':       rec.difficulty || '',
      'Total XP':         rec.totalXp || 0,
      'Datastream Score': (rec.scores && rec.scores.datastream) || 0,
      'Heist Score':      (rec.scores && rec.scores.heist) || 0,
      'Policy Score':     (rec.scores && rec.scores.policy) || 0,
      'Triage Score':     (rec.scores && rec.scores.triage) || 0,
      'HexSweep Score':   (rec.scores && rec.scores.hexsweep) || 0,
      'Grade':            rec.grade || '',
      'Passed':           rec.passed ? 'YES' : 'NO',
      'Duration (sec)':   rec.durationSec || 0,
      'Completed At':     rec.completedAt ? new Date(rec.completedAt).toISOString() : '',
      'Signed In At':     rec.signedInAt ? new Date(rec.signedInAt).toISOString() : '',
    });
  }

  function postPacket(p) {
    if (!p) return;
    // Accept both the bundle's canonical shape (text/kind/anon/student/sentAt/xp)
    // and the legacy compat shape (message/type/anonymous/studentName/.../awardedXp).
    const type        = p.kind || p.type || '';
    const message     = p.text || p.message || '';
    const isAnon      = (p.anon !== undefined) ? !!p.anon : !!p.anonymous;
    const phaseSrc    = p.phase || p.srcPhase || '';
    const submittedAt = p.sentAt || p.submittedAt;
    const xp          = (p.xp !== undefined) ? p.xp : p.awardedXp;
    const studentName = p.student ? p.student.name    : (p.studentName    || '');
    const studentEmail= p.student ? p.student.email   : (p.studentEmail   || '');
    const studentSec  = p.student ? p.student.section : (p.studentSection || '');
    postFields(PACKETS_ACTION, PACKETS_ENTRIES, {
      'Type':          (type === 'suggestion' || type === 'Suggestion') ? 'Suggestion' : 'Question',
      'Tag':           p.tag || 'other',
      'Message':       message,
      'Source Phase':  phaseSrc,
      'Anonymous':     isAnon ? 'YES' : 'NO',
      'Student Name':  studentName,
      'Student Email': studentEmail,
      'Section':       studentSec,
      'Squad Name':    p.squadName || (p.role || ''),
      'Awarded XP':    xp || 0,
      'Submitted At':  submittedAt ? new Date(submittedAt).toISOString() : '',
    });
  }

  window.SylFormsSync = { postCompletion, postPacket };
})();
