// Auth glue for the static-HTML app: a React hook that tracks the Clerk session,
// helpers to open Clerk's sign-in/up/profile flows, and a tiny same-origin API
// client (cookie auth) used to persist user data server-side.

async function apiReq(method, path, body) {
  // cache:"no-store" is essential: same-origin GETs here are otherwise served
  // from the HTTP cache as 304s with a STALE body, so freshly-corrected
  // server data (e.g. each favorite's own search prompt) never reaches the UI.
  var opt = { method: method, credentials: "include", cache: "no-store", headers: {} };
  if (body !== undefined) {
    opt.headers["Content-Type"] = "application/json";
    opt.body = JSON.stringify(body);
  }
  var r = await fetch(path, opt);
  if (!r.ok) {
    var err = new Error(method + " " + path + " -> " + r.status);
    err.status = r.status;
    throw err;
  }
  if (r.status === 204) return null;
  return r.json().catch(function () { return null; });
}

const api = {
  get: function (p) { return apiReq("GET", p); },
  post: function (p, b) { return apiReq("POST", p, b); },
  patch: function (p, b) { return apiReq("PATCH", p, b); },
  del: function (p) { return apiReq("DELETE", p); },
};

// Tracks the loaded Clerk session. `ready` flips true once the SDK has loaded;
// `user` is the Clerk user object (or null when signed out).
function useAuth() {
  const [state, setState] = React.useState(function () {
    return {
      ready: !!(window.Clerk && window.Clerk.loaded),
      user: (window.Clerk && window.Clerk.user) || null,
    };
  });
  React.useEffect(function () {
    let unsub = function () {};
    function attach(clerk) {
      setState({ ready: true, user: clerk.user || null });
      unsub = clerk.addListener(function (res) {
        setState({ ready: true, user: (res && res.user) || clerk.user || null });
      });
    }
    window.__onClerkReady(attach);
    return function () { unsub(); };
  }, []);
  return state;
}

// Open OUR OWN auth UI — never Clerk's hosted forms. On landing pages the shared
// modal (landing.js) exposes window.namitOpenAuth; inside the SaaS app the custom
// LoginGate is shown automatically whenever the visitor is signed out, so simply
// being here means the right form is already (or about to be) on screen.
function openCustomAuth(register) {
  if (typeof window.namitOpenAuth === "function") { window.namitOpenAuth(!!register, false); return; }
  if (window.location.pathname.indexOf("/app") === -1) { window.location.href = "/app"; }
  // else: already on /app — the signed-out gate renders the custom auth form.
}

const authActions = {
  signIn: function () { openCustomAuth(false); },
  signUp: function () { openCustomAuth(true); },
  signOut: function () { window.__onClerkReady(function (c) { c.signOut(); }); },
  manage: function () { window.__onClerkReady(function (c) { c.openUserProfile({}); }); },
};

// Map a Clerk user to the small shape the UI needs.
function authProfile(user) {
  if (!user) return null;
  const email =
    (user.primaryEmailAddress && user.primaryEmailAddress.emailAddress) ||
    (user.emailAddresses && user.emailAddresses[0] && user.emailAddresses[0].emailAddress) ||
    "";
  const name =
    (user.fullName && user.fullName.trim()) ||
    [user.firstName, user.lastName].filter(Boolean).join(" ").trim() ||
    user.username ||
    (email ? email.split("@")[0] : "") ||
    "Account";
  return { name: name, email: email, imageUrl: user.imageUrl || "" };
}

Object.assign(window, { useAuth: useAuth, authActions: authActions, api: api, authProfile: authProfile });
