/* Viamar — offline payment status + "I've sent payment" (shared desktop/mobile).
 *
 * Viamar does not collect payments online. A customer can REPORT a payment they
 * sent (e-transfer / wire / cheque / other); only Viamar staff record whether
 * accounting received it. Wording never says "paid" unless staff recorded
 * 'offline_received'.
 *
 * window.ViamarOfflinePayment = { statusFor(s), canReport(s), formatDate(v), ReportForm }
 */
(function () {
  var METHODS = [['etransfer', 'Interac e-Transfer'], ['wire', 'Wire transfer'], ['cheque', 'Cheque'], ['other', 'Other']];
  function methodLabel(m) { var hit = METHODS.find(function (x) { return x[0] === m; }); return hit ? hit[1] : 'payment'; }
  function formatDate(v) {
    if (!v) return null;
    var d = new Date(/^\d{4}-\d{2}-\d{2} \d/.test(String(v)) ? String(v).replace(' ', 'T') + 'Z' : v);
    if (isNaN(d.getTime())) return null;
    return d.toLocaleDateString('en-CA', { month: 'short', day: 'numeric', year: 'numeric' });
  }

  // Latest recorded offline payment state for a case, or null when nothing is on file.
  function statusFor(s) {
    var p = s && s.offlinePayment;
    if (!p || typeof p.status !== 'string') return null;
    var on = formatDate(p.at);
    if (p.status === 'offline_received') {
      return { tone: 'ok', badge: 'Payment received', line: 'Payment received — recorded by Viamar' + (on ? ' on ' + on : '') + '.' };
    }
    if (p.status === 'customer_reported') {
      return { tone: 'pending', badge: 'Payment reported', line: 'You reported a payment by ' + methodLabel(p.method) + (on ? ' on ' + on : '') + '. Saved for Viamar to review.' };
    }
    if (p.status === 'offline_not_received') {
      return { tone: 'pending', badge: 'Not received yet', line: 'Viamar has not recorded this payment as received yet. Contact your specialist if you already sent it.' };
    }
    return null;
  }

  // A released (priced) quote can be reported, unless accounting already received it
  // or a report is already waiting for accounting.
  function canReport(s) {
    if (!s) return false;
    var price = s.finalPrice != null ? s.finalPrice : s.final_price;
    if (!(s.priced && price != null && isFinite(Number(price)))) return false;
    var st = s.offlinePayment && s.offlinePayment.status;
    return st !== 'offline_received' && st !== 'customer_reported';
  }

  function ReportForm(props) {
    var s = props.s;
    var compact = !!props.compact;
    var caseId = s ? (s.quote_id || s.id) : null;
    // Scoped to the current session as well as the case, so a key saved under one
    // session is never replayed by another.
    var sessionScope = null;
    try { var sess = window.ViamarAPI && ViamarAPI.session ? ViamarAPI.session() : null; sessionScope = sess && sess.session_id ? String(sess.session_id) : null; } catch (x) {}
    var keyName = 'viamar.paymentNotice.pending.' + (sessionScope ? sessionScope + '.' : '') + caseId;
    var bodyName = keyName + '.body';
    var store = function (op, k, v) { try { return op === 'get' ? localStorage.getItem(k) : op === 'set' ? localStorage.setItem(k, v) : localStorage.removeItem(k); } catch (x) { return null; } };
    // The details of a report attempt whose key is not yet confirmed saved.
    var savedBody = function () { var raw = store('get', bodyName); if (!raw) return null; try { return JSON.parse(raw); } catch (x) { return null; } };
    var initial = savedBody();
    var useState = React.useState;
    var _o = useState(!!initial), open = _o[0], setOpen = _o[1];
    var _m = useState(initial && initial.method ? initial.method : 'etransfer'), method = _m[0], setMethod = _m[1];
    var _d = useState(initial && initial.paid_on ? initial.paid_on : ''), paidOn = _d[0], setPaidOn = _d[1];
    var _r = useState(initial && initial.reference ? initial.reference : ''), reference = _r[0], setReference = _r[1];
    var _b = useState(false), busy = _b[0], setBusy = _b[1];
    var _e = useState(null), err = _e[0], setErr = _e[1];
    var _k = useState(false), done = _k[0], setDone = _k[1];
    var _c = useState(false), conflict = _c[0], setConflict = _c[1];
    if (!canReport(s) && !done) return null;
    var field = { fontFamily: FB, fontSize: 13, padding: '8px 10px', borderRadius: 9, border: '1px solid ' + (T.line2 || '#dde3ea'), background: '#fff', color: T.ink || '#0A1B2E', width: '100%', boxSizing: 'border-box' };
    var btn = function (primary) { return { appearance: 'none', border: primary ? 0 : '1px solid ' + (T.line2 || '#dde3ea'), background: primary ? (T.navy || '#0A1B2E') : '#fff', color: primary ? '#fff' : (T.ink || '#0A1B2E'), fontFamily: FB, fontWeight: 700, fontSize: 12.5, padding: '8px 14px', borderRadius: 999, cursor: busy ? 'wait' : 'pointer' }; };
    if (done) {
      return React.createElement('div', { style: { fontFamily: FB, fontSize: 12.5, color: T.body || '#33475b', marginTop: 10 } },
        'Thanks — saved for Viamar to review.');
    }
    if (!open) {
      return React.createElement('button', { type: 'button', onClick: function () { setOpen(true); }, style: Object.assign(btn(false), { marginTop: 10 }) }, "I've sent payment");
    }
    // One key per logical report, kept with its original details until the server
    // confirms the save. Retry, double click, reload or a lost response replays the
    // SAME report; only an explicit "Start a new report" creates a new key.
    var pendingKey = function () {
      var k = store('get', keyName);
      if (!k) {
        k = (window.crypto && crypto.randomUUID) ? crypto.randomUUID() : ('pn-' + Date.now() + '-' + Math.random().toString(36).slice(2, 10));
        store('set', keyName, k);
      }
      return k;
    };
    var currentBody = function () { return { method: method, paid_on: paidOn || null, reference: reference.trim() || null }; };
    var same = function (a, b) { return !!a && !!b && a.method === b.method && (a.paid_on || null) === (b.paid_on || null) && (a.reference || null) === (b.reference || null); };
    var describe = function (b) { return methodLabel(b.method) + (b.paid_on ? ', ' + b.paid_on : '') + (b.reference ? ', ref ' + b.reference : ''); };
    var send = function (body) {
      setBusy(true); setErr(null);
      return ViamarAPI.reportOfflinePayment(caseId, { request_key: pendingKey(), method: body.method, paid_on: body.paid_on || undefined, reference: body.reference || undefined })
        .then(function () {
          store('remove', keyName); store('remove', bodyName);
          setConflict(false); setDone(true);
          if (window.ViamarStore && ViamarStore.syncCustomerState) return ViamarStore.syncCustomerState().catch(function () {});
        })
        .catch(function (error) {
          // Keep the key and original details; a 409 means this report was saved
          // with other details. The customer chooses explicitly what to do next.
          if (error && error.status === 409) {
            setConflict(true);
            setErr('A report was already saved with different details. Keep it, or start a new report with these details.');
          } else {
            setErr((error && error.message) || 'Could not send. Please call 1-800-277-7570.');
          }
        })
        .then(function () { setBusy(false); });
    };
    var submit = function (e) {
      if (e && e.preventDefault) e.preventDefault();
      if (busy) return;
      var body = currentBody();
      var earlier = savedBody();
      if (earlier && !same(earlier, body)) {
        setConflict(true);
        setErr('You have an earlier report that may already be saved (' + describe(earlier) + '). Send it again, or start a new report with these details.');
        return;
      }
      if (!earlier) store('set', bodyName, JSON.stringify(body));
      return send(body);
    };
    var resendEarlier = function () { var earlier = savedBody(); if (earlier) { setMethod(earlier.method); setPaidOn(earlier.paid_on || ''); setReference(earlier.reference || ''); return send(earlier); } };
    var startNew = function () {
      store('remove', keyName); store('remove', bodyName); setConflict(false); setErr(null);
      var body = currentBody(); store('set', bodyName, JSON.stringify(body));
      return send(body);
    };
    return React.createElement('form', { onSubmit: submit, style: { marginTop: 10, display: 'grid', gap: 8, gridTemplateColumns: compact ? '1fr' : '1fr 1fr 1fr' } },
      React.createElement('label', { style: { display: 'grid', gap: 4, fontFamily: FM, fontSize: 10, color: T.muted || '#5b6b7d', textTransform: 'uppercase', letterSpacing: 0.5 } }, 'Method',
        React.createElement('select', { value: method, onChange: function (e) { setMethod(e.target.value); }, style: field },
          METHODS.map(function (m) { return React.createElement('option', { key: m[0], value: m[0] }, m[1]); }))),
      React.createElement('label', { style: { display: 'grid', gap: 4, fontFamily: FM, fontSize: 10, color: T.muted || '#5b6b7d', textTransform: 'uppercase', letterSpacing: 0.5 } }, 'Date sent',
        React.createElement('input', { type: 'date', value: paidOn, onChange: function (e) { setPaidOn(e.target.value); }, style: field })),
      React.createElement('label', { style: { display: 'grid', gap: 4, fontFamily: FM, fontSize: 10, color: T.muted || '#5b6b7d', textTransform: 'uppercase', letterSpacing: 0.5 } }, 'Reference (optional)',
        React.createElement('input', { type: 'text', maxLength: 120, value: reference, placeholder: 'e.g. e-Transfer reference', onChange: function (e) { setReference(e.target.value); }, style: field })),
      React.createElement('div', { style: { gridColumn: '1 / -1', display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' } },
        React.createElement('button', { type: 'submit', disabled: busy, style: btn(true) }, busy ? 'Sending…' : 'Send to Viamar'),
        React.createElement('button', { type: 'button', disabled: busy, onClick: function () { setOpen(false); }, style: btn(false) }, 'Cancel'),
        React.createElement('span', { style: { fontFamily: FB, fontSize: 11.5, color: T.muted || '#5b6b7d' } }, 'This tells Viamar you sent it. It is not a payment.')),
      err ? React.createElement('div', { role: 'alert', style: { gridColumn: '1 / -1', fontFamily: FB, fontSize: 12, color: T.red || '#DD1C24' } }, err) : null,
      conflict ? React.createElement('div', { style: { gridColumn: '1 / -1', display: 'flex', gap: 8, flexWrap: 'wrap' } },
        savedBody() ? React.createElement('button', { type: 'button', disabled: busy, onClick: resendEarlier, style: btn(false) }, 'Send earlier report again') : null,
        React.createElement('button', { type: 'button', disabled: busy, onClick: startNew, style: btn(true) }, 'Start a new report')) : null);
  }

  window.ViamarOfflinePayment = { statusFor: statusFor, canReport: canReport, formatDate: formatDate, ReportForm: ReportForm, methodLabel: methodLabel };
})();
