// Customer session for the support portal. A low-friction "login": the person
// gives a ticket number + work email; we verify the ticket belongs to that
// email, then scope their workspace to that email. No password (knowing a valid
// ticket + the email on it is the gate) — deliberately low-friction.
//
// Verification is server-side against Jira when configured; otherwise it falls
// back to the local ticket mirror (demo). Identity also feeds agent-chat +
// dashboards via NS.session.identity(); the embedded widget (no portal session)
// falls back to NS.ME.

(function () {
  const LS = "ns_customer_session_v1";

  function get() { try { return JSON.parse(localStorage.getItem(LS) || "null"); } catch (e) { return null; } }
  function set(s) { try { localStorage.setItem(LS, JSON.stringify(s)); } catch (e) {} }
  function clear() { try { localStorage.removeItem(LS); } catch (e) {} }

  function accountFromEmail(e) {
    const d = (String(e).split("@")[1] || "").split(".")[0];
    return d ? d.charAt(0).toUpperCase() + d.slice(1) : "";
  }
  function nameFromEmail(e) {
    const p = (String(e).split("@")[0] || "").replace(/[._]+/g, " ").trim();
    return p ? p.replace(/\b\w/g, (c) => c.toUpperCase()) : "there";
  }

  // Who the chat/dashboards should act as. Portal session wins; else the demo ME.
  function identity() {
    const s = get();
    if (s && s.email) {
      return { email: s.email, account: s.account || accountFromEmail(s.email), name: s.name || nameFromEmail(s.email) };
    }
    return (window.NS && window.NS.ME) || { email: "", account: "", name: "there" };
  }

  // Verify a ticket belongs to an email. Server (Jira) first, then local mirror.
  async function verify(ticketRaw, emailRaw) {
    const ticket = String(ticketRaw || "").trim().toUpperCase().replace(/[^A-Z0-9-]/g, "");
    const email = String(emailRaw || "").trim().toLowerCase();
    if (!ticket || !email) return { ok: false, reason: "missing" };
    try {
      const r = await fetch("/api/v1/verify", {
        method: "POST", headers: { "content-type": "application/json" },
        body: JSON.stringify({ ticket, email }),
      });
      if (r.ok) { const d = await r.json(); return { ok: !!d.verified, server: true }; }
      if (r.status === 401) return { ok: false, reason: "unauthorized" };
      // 503 not configured -> fall through to the local mirror
    } catch (e) { /* fall through */ }
    const t = window.NS.tickets && window.NS.tickets.get(ticket);
    if (t && String(t.reporter || "").toLowerCase() === email) return { ok: true, server: false };
    return { ok: false, reason: "not_found" };
  }

  window.NS = Object.assign(window.NS || {}, {
    session: { get, set, clear, identity, verify },
  });
})();
