// Authentication context — session, agency-admin status, workspace memberships,
// and the *currently selected* workspace (the one whose data the /app/* pages
// render). The selection is persisted to localStorage so refreshing keeps you
// in the same workspace.
const AuthContext = React.createContext(null);
const CURRENT_WS_KEY = "vale_current_ws";

function AuthProvider({ children }) {
  const [loading, setLoading] = useState(true);
  const [session, setSession] = useState(null);
  const [isAgencyAdmin, setIsAgencyAdmin] = useState(false);
  const [adminName, setAdminName] = useState(null);
  const [memberships, setMemberships] = useState([]);
  const [currentWorkspace, _setCurrentWorkspace] = useState(null);

  // Wrap setter so localStorage stays in sync.
  const setCurrentWorkspace = useCallback((ws) => {
    if (ws && ws.id) localStorage.setItem(CURRENT_WS_KEY, ws.id);
    else             localStorage.removeItem(CURRENT_WS_KEY);
    _setCurrentWorkspace(ws || null);
  }, []);

  useEffect(() => {
    let cancelled = false;

    async function hydrate(s) {
      if (!s) {
        setSession(null);
        setIsAgencyAdmin(false);
        setAdminName(null);
        setMemberships([]);
        _setCurrentWorkspace(null);
        setLoading(false);
        return;
      }
      setSession(s);

      const [adminRes, memberRes] = await Promise.all([
        SB.from('agency_admins').select('user_id, name').eq('user_id', s.user.id).maybeSingle(),
        SB.from('workspace_members')
          .select('workspace_id, role, name, permissions, workspaces ( id, name, slug, industry, timezone )')
          .eq('user_id', s.user.id)
      ]);
      if (cancelled) return;

      const isAdmin = !!adminRes.data;
      const mems = memberRes.data || [];
      setIsAgencyAdmin(isAdmin);
      setAdminName(adminRes.data?.name || null);
      setMemberships(mems);

      // Resolve current workspace:
      //   1. If localStorage has an id we can read (RLS allows), use it.
      //   2. Otherwise, fall back to the user's first membership.
      //   3. Otherwise leave it null (agency admin with no pick yet).
      const storedId = localStorage.getItem(CURRENT_WS_KEY);
      let ws = null;
      if (storedId) {
        const r = await SB.from('workspaces').select('*').eq('id', storedId).maybeSingle();
        if (!cancelled) ws = r.data || null;
      }
      if (!ws && mems.length > 0) ws = mems[0].workspaces;
      if (cancelled) return;

      if (ws && ws.id) localStorage.setItem(CURRENT_WS_KEY, ws.id);
      else             localStorage.removeItem(CURRENT_WS_KEY);
      _setCurrentWorkspace(ws);
      setLoading(false);
    }

    SB.auth.getSession().then((res) => hydrate(res.data.session));
    const sub = SB.auth.onAuthStateChange((_event, s) => hydrate(s));

    return () => {
      cancelled = true;
      sub.data.subscription.unsubscribe();
    };
  }, []);

  const value = {
    loading, session, isAgencyAdmin, adminName, memberships,
    currentWorkspace, setCurrentWorkspace,
  };
  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

// Pick the best display name for the current user.
// Priority: member name in the current workspace → agency admin name →
// auth user_metadata.full_name → email username → "there".
function displayNameFor(auth) {
  if (!auth || !auth.session) return null;
  const ws = auth.currentWorkspace;
  if (ws) {
    const mem = (auth.memberships || []).find(m => m.workspace_id === ws.id);
    if (mem?.name) return mem.name;
  }
  if (auth.adminName) return auth.adminName;
  const meta = auth.session.user?.user_metadata || {};
  if (meta.full_name) return meta.full_name;
  if (meta.name)      return meta.name;
  const email = auth.session.user?.email || "";
  if (email.includes("@")) return email.split("@")[0];
  return null;
}

function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error("useAuth must be used inside <AuthProvider>");
  return ctx;
}

// Convenience helpers used by login/logout buttons.
async function signInWithPassword(email, password) {
  return SB.auth.signInWithPassword({ email, password });
}
async function signOut() {
  localStorage.removeItem(CURRENT_WS_KEY);
  return SB.auth.signOut();
}

// Where to land after a successful sign-in.
function defaultHomeFor(auth) {
  if (auth.isAgencyAdmin) return "/agency/clients";
  if (auth.memberships.length > 0) return "/app/dashboard";
  return "/onboarding";
}

function AuthSplash() {
  return (
    <div className="min-h-screen flex items-center justify-center bg-paper">
      <div className="flex items-center gap-2 text-[12px] text-ink/45">
        <span className="h-1.5 w-1.5 rounded-full bg-ink/35 pulse-dot" />
        Loading
      </div>
    </div>
  );
}

Object.assign(window, { AuthProvider, useAuth, signInWithPassword, signOut, defaultHomeFor, displayNameFor, AuthSplash });
