// assets/js/flow/create.js


// --- Title safety net: strip HTML, collapse whitespace, cap length
function sanitizeTaskTitle(title, maxLen = 140) {
  if (typeof title !== 'string') return '';
  let s = title;

  // Strip basic HTML / entities
  s = s
    .replace(/<\/?[^>]+>/g, ' ')
    .replace(/&nbsp;/gi, ' ')
    .replace(/&amp;/gi, '&');

  // Single-line, tidy whitespace & dashes
  s = s
    .replace(/[\r\n\t]+/g, ' ')
    .replace(/\s{2,}/g, ' ')
    .replace(/\s*–\s*(?:–\s*)+/g, ' – ')
    .replace(/(?:\s*–\s*)+$/g, '')
    .trim();

  if (s.length > maxLen) s = s.slice(0, maxLen).trim();
  return s;
}





(function (w) {
  function afbMakeRequestId() {
    if (w.crypto && typeof w.crypto.randomUUID === 'function') {
      return `cli_${w.crypto.randomUUID().replace(/-/g, '')}`;
    }

    const rand = Math.random().toString(36).slice(2, 12);
    return `cli_${Date.now()}_${rand}`;
  }

  function inferHttpCodeFromRawBody(rawBody) {
    const text = typeof rawBody === 'string' ? rawBody : '';
    if (!text) return 0;

    if (/Connection Timed Out/i.test(text) || /Gateway Timeout/i.test(text)) {
      return 504;
    }
    if (/Bad Gateway/i.test(text)) {
      return 502;
    }

    return 0;
  }

  function isTransientCreateFailure(code, message, rawBody) {
    const httpCode = Number(code || 0);
    if ([0, 408, 425, 429, 500, 502, 503, 504].includes(httpCode)) {
      return true;
    }

    const probe = `${message || ''}\n${rawBody || ''}`;
    return /timed\s*out|timeout|gateway|temporar(?:y|ily)|connection\s+reset|connection\s+aborted/i.test(probe);
  }

  function buildCreateError({ message, code = 0, rawBody = '', requestId = '' }) {
    const err = new Error(message || 'Task create failed');
    err.name = 'AfbCreateError';
    err.code = Number(code || 0);
    err.requestId = requestId || '';
    err.rawBody = rawBody || '';
    err.isTransient = isTransientCreateFailure(err.code, err.message, rawBody);
    return err;
  }

  function parseAjaxJsonSafely(rawBody) {
    const text = typeof rawBody === 'string' ? rawBody : '';
    if (!text) return null;

    try {
      return JSON.parse(text);
    } catch (e) {
      // Some environments prepend HTML/debug output before the real JSON.
      // Try to recover by parsing from the first JSON object marker.
      const start = text.indexOf('{"success"');
      if (start >= 0) {
        const candidate = text.slice(start);
        try {
          return JSON.parse(candidate);
        } catch (e2) {
          const end = candidate.lastIndexOf('}');
          if (end > 0) {
            try {
              return JSON.parse(candidate.slice(0, end + 1));
            } catch (e3) {
              return null;
            }
          }
        }
      }
      return null;
    }
  }

  async function afbCreateTaskFast({ ajaxUrl, projectId, taskName, uploadCount = 0, payload = {}, requestId = '' }) {
    const fd = new FormData();
    fd.append('action', 'afb_create_task_fast');
    fd.append('project_id', projectId || '');
    fd.append('task_name',  taskName   || '');
    fd.append('upload_count', String(uploadCount));
    if (requestId) fd.append('request_id', String(requestId));

    // pass-through payload fields (ai_summary, submitted_copy_html, etc.)
    Object.entries(payload || {}).forEach(([k, v]) => fd.append(k, v));

    let res;
    try {
      res = await fetch(ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' });
    } catch (networkErr) {
      throw buildCreateError({
        message: 'Network error while creating task. Please check your connection and try again.',
        code: 0,
        rawBody: String((networkErr && networkErr.message) || ''),
        requestId
      });
    }

    // Read raw body once and try parse JSON. If parsing fails, include snippet in thrown error.
    let json = null;
    let rawBody = '';
    try {
      rawBody = await res.text();
      json = parseAjaxJsonSafely(rawBody);
    } catch (e) {
      json = null;
      rawBody = '';
    }

    if (!json || json.success !== true) {
      const data = (json && json.data) || {};
      const code = Number(data.http_code || res.status || inferHttpCodeFromRawBody(rawBody) || 0);
      const msg  = data && data.message ? data.message : 'Task create failed';
      let extra = '';
      if (!json && rawBody) {
        const snippet = rawBody.trim().slice(0, 1200).replace(/\s+/g, ' ');
        extra = ` — response body: ${snippet}`;
      }
      throw buildCreateError({
        message: `${msg}${code ? ` (HTTP ${code})` : ''}${extra}`,
        code,
        rawBody,
        requestId
      });
    }

    const { request_id, task_gid, gateway_creation_mode } = json.data || {};
    if (!request_id || !task_gid) throw new Error('Malformed create response');
    return { request_id, task_gid, gateway_creation_mode };
  }

  w.afbFlowCreate = { afbCreateTaskFast, afbMakeRequestId };
})(window);
