/* hovex-api.jsx — tiny client for the Hovex Express VPS API.

   The backend is a SEPARATE origin (api.advancedflow.cloud), not the same-origin
   Vercel Functions. All calls read the base URL from window.AF_ENV.HOVEX_API_BASE
   so it's swappable without touching components.

   No database on the server: the browser is the source of truth for the intake
   JSON. We persist { state, token } in localStorage and send them on every turn.
   Resume = same browser reloads from localStorage. */

const HOVEX_API_BASE =
  (window.AF_ENV && window.AF_ENV.HOVEX_API_BASE) || "https://api.advancedflow.cloud";

const HOVEX_STATE_KEY = "hovex-intake-state";
const HOVEX_TOKEN_KEY = "hovex-intake-token";
// Result of /intake/complete — carries the client's place in the waiting list.
// Kept SEPARATE from the session on purpose: #listo needs it to survive the
// session being cleared, and a reload of #listo must not lose the number.
const HOVEX_FINISH_KEY = "hovex-intake-finish";

// ── localStorage persistence ────────────────────────────────────────────────
function saveSession(state, token) {
  try {
    localStorage.setItem(HOVEX_STATE_KEY, JSON.stringify(state));
    if (token) localStorage.setItem(HOVEX_TOKEN_KEY, token);
  } catch (_e) { /* storage full / disabled — the chat still works in-memory */ }
}

function loadSession() {
  try {
    const raw = localStorage.getItem(HOVEX_STATE_KEY);
    const token = localStorage.getItem(HOVEX_TOKEN_KEY) || "";
    return { state: raw ? JSON.parse(raw) : null, token };
  } catch (_e) {
    return { state: null, token: "" };
  }
}

function clearSession() {
  try {
    localStorage.removeItem(HOVEX_STATE_KEY);
    localStorage.removeItem(HOVEX_TOKEN_KEY);
  } catch (_e) { /* ignore */ }
}

function saveFinish(result) {
  try { localStorage.setItem(HOVEX_FINISH_KEY, JSON.stringify(result || {})); }
  catch (_e) { /* storage full / disabled — #listo falls back to its no-number copy */ }
}

function loadFinish() {
  try {
    const raw = localStorage.getItem(HOVEX_FINISH_KEY);
    return raw ? JSON.parse(raw) : null;
  } catch (_e) { return null; }
}

function clearFinish() {
  try { localStorage.removeItem(HOVEX_FINISH_KEY); } catch (_e) { /* ignore */ }
}

// ── HTTP helpers ─────────────────────────────────────────────────────────────
async function postJSON(path, body, token) {
  const headers = { "Content-Type": "application/json" };
  if (token) headers["Authorization"] = `Bearer ${token}`;
  const res = await fetch(`${HOVEX_API_BASE}${path}`, {
    method: "POST",
    headers,
    body: JSON.stringify(body || {}),
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) {
    const err = new Error((data && data.error) || `HTTP ${res.status}`);
    err.status = res.status;
    err.code = data && data.error;
    throw err;
  }
  return data;
}

// ── Public API ───────────────────────────────────────────────────────────────
const HovexAPI = {
  base: HOVEX_API_BASE,
  saveSession, loadSession, clearSession,
  saveFinish, loadFinish, clearFinish,

  // Create a new intake from the /crear lead form. Returns { state, token }.
  async createIntake(payload) {
    const data = await postJSON("/api/intake", payload);
    if (data && data.state && data.token) saveSession(data.state, data.token);
    // A new project starts with a clean slate: a stale queue number from a
    // previous run would show up on #listo as if it belonged to this one.
    clearFinish();
    return data;
  },

  // Advance one conversation turn. Sends the whole state back each time.
  async turn(state, token, userMessage) {
    const data = await postJSON("/api/intake/turn", { state, userMessage }, token);
    if (data && data.state) saveSession(data.state, token);
    return data;
  },

  // Upload an asset (logo/photo). Uses multipart; handled in Phase 4.
  async uploadAsset(token, intakeId, kind, file) {
    const form = new FormData();
    form.append("intake_id", intakeId);
    form.append("kind", kind); // "logo" | "photo"
    form.append("file", file);
    const headers = {};
    if (token) headers["Authorization"] = `Bearer ${token}`;
    const res = await fetch(`${HOVEX_API_BASE}/api/intake/asset`, {
      method: "POST", headers, body: form,
    });
    const data = await res.json().catch(() => ({}));
    if (!res.ok) throw new Error((data && data.error) || `HTTP ${res.status}`);
    if (data && data.state) saveSession(data.state, token);
    return data;
  },

  // Finalize: compile the build package, forward it to the company dashboard
  // and get back the client's place in the waiting list. Persisted so #listo
  // can render the number after a reload.
  async complete(state, token) {
    const data = await postJSON("/api/intake/complete", { state }, token);
    saveFinish(data);
    return data;
  },
};

Object.assign(window, { HovexAPI });
